Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is grpc channel/stub thread safe in csharp

is grpc channel thread safe in csharp, or more generally in any language depend on C core version;

for the following code: 1) is channel thread safe? 2) is client thread safe?

        Channel channel = new Channel("127.0.0.1:50051", ChannelCredentials.Insecure);

        Task task1 = Task.Factory.StartNew(() =>
        {

            var client = new Greeter.GreeterClient(channel);
            String user = "you";
            var reply = client.SayHello(new HelloRequest {Name = user});
            Console.WriteLine("Greeting: " + reply.Message);
        });

        Task task2 = Task.Factory.StartNew(() =>
        {

            var client = new Greeter.GreeterClient(channel);
            String user = "you";
            var secondReply = client.SayHelloAgain(new HelloRequest {Name = user});
            Console.WriteLine("Greeting: " + secondReply.Message);

        });

        task1.Wait();
        task2.Wait();
        channel.ShutdownAsync().Wait();
        Console.WriteLine("Press any key to exit...");
        Console.ReadKey();
like image 867
lcm Avatar asked Mar 07 '23 05:03

lcm


1 Answers

Yes, channel and client(stub for other languages) are both thread-safe in csharp.

The channel is an abstraction of long-lived connection to remote server. More client objects can reuse the same channel, even with different gRPC servers so long as they have the same address (For example, use Envy as sidecar in Kubernetes, server addresses are all localhost:envoy-port).

The documentation explicitly states that Creating a channel is an expensive operation compared to invoking a remote call so in general you should reuse a single channel for as many calls as possible. Here's its source code. You can see that its shared data can be safety accessed by multiple threads.

The Client's base class ClientBase<T> and ClientBase are both thread-safe you can verify it from their source code. So client is thread-safe if you just use the auto-generated one and the client-side interceptors you added are thread-safe too.

like image 170
Feiyu Zhou Avatar answered Mar 10 '23 02:03

Feiyu Zhou