Search code examples
c#.net-coregrpcgrpc-dotnet

How do I retrieve streaming results using Grpc in .Net Core?


I am building a .NetCore application using gRPC.

I'm having issues constructing code to handle streaming results.

Consider the following protobuf definition:

service SampleService
{
    rpc RegisterClient(G_ClientRequest) returns (stream G_ClientResponse) { }
}

Here is a code snippet to read results from the stream:

public ConnectToClient()
{
    var results = Client.RegisterClient(new G_ClientRequest() 
    { 
        ClientName = "Foo",
        DateTimeStamp = new Google.Protobuf.WellKnownTypes.Timestamp()
    });
    
    var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
    foreach (var result in results.ResponseStream.ReadAllAsync(cancellationToken: cts.Token))
    {

    }   
}

I've been googling around and found something similar to my above code for handling streaming results. However the code does not compile. ReadAllAsync() is not available in the interface definition for IAsyncStreamReader.

Is this functionality not available/supported in .Net Core? I'm using the latest stable version of Grpc (2.38).

If this is not available to me, how do I retrieve results from the ResponseStream in .Net Core?

Thx, JohnB


Solution

  • ReadAllAsync is an extension included in Grpc.Core, if you have installed the Nuget package Grpc.Net.Client just add:

    using Grpc.Core;