# Unity使用异步grpc
(金庆的专栏 2020.6)
Unity 保证 async 方法运行在主线程中,所以用异步方式调用 grpc 可以大大简化网络通信的代码。
以下示例中将 grpc 的 RouteGuide 示例移到 Unity 中运行。
https://github.com/grpc/grpc/tree/master/examples/csharp/RouteGuide
其中 Main() 中的代码移到 Start() 中运行,阻塞调用改成异步调用, GetFeature() 改成 GetFeatureAsync()。
完整代码见:https://gitee.com/jinq0123/unity-grpc-async
```
using Grpc.Core;
using Routeguide;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using static Routeguide.Program;
public class Test : MonoBehaviour
{
// Start is called before the first frame update
async void Start()
{
var channel = new Channel("127.0.0.1:50052", ChannelCredentials.Insecure);
var client = new RouteGuideClient(new RouteGuide.RouteGuideClient(channel));
// Looking for a valid feature
await client.GetFeatureAsync(409146138, -746188906);
// Feature missing.
await client.GetFeatureAsync(0, 0);
// Looking for features between 40, -75 and 42, -73.
await client.ListFeatures(400000000, -750000000, 420000000, -730000000);
// Record a few randomly selected points from the features file.
await client.RecordRoute(RouteGuideUtil.LoadFeatures(), 10);
// Send and receive some notes.
await client.RouteChat();
await channel.ShutdownAsync();
Debug.Log("End of test.");
}
}
```