gRPC and its idea to describe an API in a standardized file, which can generate both client and server code to interact in different languages is a compelling idea.
In this post, I would like to have a quick look at the experience you would have with gRPC streaming capability and the new C# 8 async streams, which sounds like a perfect match.

I am using the .NET Core CLI to create the solution with two projects, one for the server called grpcAsyncStreamServer and one for the client grpcAsyncStreamClient. By the way, do you know you can get tab completion of .NET Core CLI commands? Very handy.

Server

I am using the default gRPC .NET Core template to generate the server part. The template creates a greet.proto file which I will duplicate between the server and the client project. As I want to experience with the streaming capability of gRPC, I am modifying the greet.proto file adding the keyword stream in front of the SayHello HelloReply response.

Server streaming RPC
A server-streaming RPC is similar to our simple example, except the server sends back a stream of responses after getting the client’s request message. After sending back all its responses, the server’s status details (status code and optional status message) and optional trailing metadata are sent back to complete on the server side. The client completes once it has all the server’s responses.

Here is how the greet.proto looks like.

greet.proto
1
syntax = "proto3";
2
3
option csharp_namespace = "grpcAsyncStreamServer";
4
5
package Greet;
6
7
// The greeting service definition.
8
service Greeter {
9
  // Sends a greeting
10
  rpc SayHello (HelloRequest) returns (stream HelloReply);
11
}
12
13
// The request message containing the user's name.
14
message HelloRequest {
15
  string name = 1;
16
}
17
18
// The response message containing the greetings.
19
message HelloReply {
20
  string message = 1;
21
}

I modify the code of the GreeterService class coming from the template to stream 10 HelloReply back to the client, with a small delay of 200ms in between each string returned to simulate some work.

GreeterService.cs
1
public class GreeterService : Greeter.GreeterBase
2
{
3
    private readonly ILogger<GreeterService> _logger;
4
    public GreeterService(ILogger<GreeterService> logger)
5
    {
6
        _logger = logger;
7
    }
8
9
    public override async Task SayHello(HelloRequest request, IServerStreamWriter<HelloReply> responseStream,                                            ServerCallContext context)
10
    {
11
        foreach (var x in Enumerable.Range(1, 10))
12
        {
13
            await responseStream.WriteAsync(new HelloReply
14
            {
15
                Message = $"Hello {request.Name} {x}"
16
            });
17
18
            await Task.Delay(200);
19
        }
20
    }
21
}

Client

For the client, I am creating a new Console application and copying the greet.proto into a new folder which I name Protos. Then I need to add the dependencies that you can see on the following csproj, so that at compilation time, the proto file is projected to C# code which I can use in my code. That’s nice because it means that you also get after a first compilation IntelliSense auto-completion.

grpcAsyncStreamClient.csproj
1
<Project Sdk="Microsoft.NET.Sdk">
2
3
  <PropertyGroup>
4
    <OutputType>Exe</OutputType>
5
    <TargetFramework>netcoreapp3.0</TargetFramework>
6
  </PropertyGroup>
7
8
  <ItemGroup>
9
    <PackageReference Include="Google.Protobuf" Version="3.9.1" />
10
    <PackageReference Include="Grpc.Core" Version="2.23.0" />
11
    <PackageReference Include="Grpc.Net.Client" Version="0.2.23" />
12
    <PackageReference Include="Grpc.Tools" Version="2.23.0" />
13
  </ItemGroup>
14
15
  <ItemGroup>
16
    <Protobuf Include="Protos\greet.proto">
17
      <GrpcServices>Client</GrpcServices>
18
      <Access>Public</Access>
19
      <ProtoCompile>True</ProtoCompile>
20
      <CompileOutputs>True</CompileOutputs>
21
      <OutputDir>obj\Debug\netcoreapp3.0\</OutputDir>
22
      <Generator>MSBuild:Compile</Generator>
23
    </Protobuf>
24
  </ItemGroup>
25
  
26
</Project>

We can now use the new C# 8 Async stream to iterate on the server answers asynchronously.

C# has support for iterator methods and async methods, but no support for a method that is both an iterator and an async method. We should rectify this by allowing for await to be used in a new form of async iterator, one that returns an IAsyncEnumerable or IAsyncEnumerator rather than an IEnumerable or IEnumerator, with IAsyncEnumerable consumable in a new await foreach. An IAsyncDisposable interface is also used to enable asynchronous cleanup.

The code is greatly readable with this.

Program.cs
1
static class Program
2
{
3
    static async Task Main(string[] args)
4
    {
5
        var channel = GrpcChannel.ForAddress("https://localhost:5001");
6
        var client = new Greeter.GreeterClient(channel);
7
8
        var replies = client.SayHello(new HelloRequest { Name = "Laurent" });
9
10
        await foreach (var reply in replies.ResponseStream.ReadAllAsync())
11
        {
12
            Console.WriteLine(reply.Message);
13
        }
14
    }
15
}

Conclusion

We have seen that C# 8 Async streams are nicely integrating with gRPC streaming capabilities. And it makes code more readable!

You can get all the code on GitHub