简体   繁体   中英

Creating gRPC server with c#. Return types Task?

I created a gRPC server with C#. Quite simple. What confuses me is that the return types of all message requests are Tasks .

From the example Greeting server:

public override Task<HelloReply> SayHello(HelloRequest request, ServerCallContext context)
{
    return Task.FromResult(new HelloReply { Message = "Hello " + request.Name });
}

I wonder why the return type is not just HelloReply . I started creating my own server and continued returning Task.FromResult but actually it is not the way Task was meant to be used. So I fear I am missing something (regarding performance?). But on the other side I can not image what there could be wrong. A gRPC server is parallel itself for every request, isn't it? So I what situations is returning Task useful?

Concurrent (parallel) is different to async (Task etc); using a blocking (non-async) call means that a thread is tied up dedicated to your operation, for the duration of your operation, which is not hugely scalable considering that most real services involve external IO (databases, files, etc) - and it is here that async adds huge benefits. Threads are expensive and limited - which imposes an artificial throughput limit, which can be avoided via async. Returning something awaitable such as Task<HelloReply> or ValueTask<HelloReply> is a pre-requisite for allowing (but not demanding) things to be async.

If you don't need that (which seems unlikely): use Task.FromResult , as you are doing. Or if you're using protobuf-net.Grpc: synchronous methods are supported directly (it basically wraps it very similarly to how you're doing it).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM