Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Reuse or create new client per Grpc Unary Call

Tags:

c#

grpc

I have read the document and I don't see the details that when I make a unary call to grpc server, I create a new client or reuse a client (Channel will obviously reuse it again). As the code below, use SayHello or SayHello1. Thank you.

using System;
using Grpc.Core;
using HelloWorld;

namespace GreeterClient
{
    class Program
    {
        static Greeter.GreeterClient client;
        static Channel channel;
        public static void Main(string[] args)
        {
            channel = new Channel("127.0.0.1:50051", ChannelCredentials.Insecure);
            client = new Greeter.GreeterClient(channel);

            while (true)
            {
                try
                {
                    var name = Console.ReadLine();
                    var reply = SayHello(name);
                    Console.WriteLine(reply);
                }
                catch (RpcException ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
            channel.ShutdownAsync().Wait();

        }
        public static string SayHello(string name)
        {
            var reply = client.SayHello(new HelloRequest { Name = name });
            return reply.Message;
        }
        public static string SayHello1(string name)
        {
            var newClient = new Greeter.GreeterClient(channel);
            var reply = newClient.SayHello(new HelloRequest { Name = name });
            return reply.Message;
        }
    }
}
like image 265
PhongLt Avatar asked Oct 28 '25 05:10

PhongLt


1 Answers

Most commonly, you would reuse the same client class instance ("GreeterClient" in your case) for all calls you make. That said, creating a new "GreeterClient" instance (from a pre-existing channel) is a very cheap operation, so creating more instances of client class (e.g. due to logical structure of your code) doesn't do any harm.

Channel class is comparably much more heavyweight and you should only be creating new channel instances when you have a good reason to do so.

like image 195
Jan Tattermusch Avatar answered Oct 29 '25 17:10

Jan Tattermusch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!