In the previous post “gRPC and C# 8 Async stream“, we looked at how gRPC server stream and C# 8 Async stream work great together. In this post, we are looking at the way we can, from the client, stop the server to stream results back.
I need to extend a bit the original code of the GreeterService to take care of the client request to stop the streaming. This is done through the usage of ServerCallContext which exposes a CancellationToken.
Note: we don’t need to change anything to our greet.proto file! The cancellation capability is coming out of the box from the framework.
Then we need to check if the client requests the cancellation using IsCancellationRequested and in that case, stop writing back into the responseStream. Easy!
public class GreeterService : Greeter.GreeterBase
Imagine that we want the client to stop getting results after getting 5 responses from the server. The client needs to signal to the server to stop sending responses.
As we did for the server, we need to use cancellation token for that, which we simply pass to the ResponseStream.ReadAllAsync method.
Then we need to surround our code with try…catch catching RpcException with a status code of StatusCode.Cancelled. Easy too!
static class Program
We have seen that it is easy to cancel gRPC streaming from the client using C# 8 Async streams and cancellation token.
You can get all the code on GitHub
Thanks, Sam Macpherson for asking the question on Twitter.