.NET › gRPC Services
How do you implement server-streaming gRPC using C#'s IAsyncEnumerable<T> or IServerStreamWriter<T>?
IntermediateAnswer
A server-streaming RPC method receives an IServerStreamWriter<TResponse> parameter, calling WriteAsync() repeatedly to send each item in the stream to the client as it becomes available, with the method completing (and thus the stream ending) when the method returns -- this maps naturally onto C#'s async streaming patterns, letting a server push results incrementally rather than requiring the client to wait for the entire result set to be computed before receiving anything.
public override async Task StreamUpdates(SubscribeRequest request, IServerStreamWriter<Update> responseStream, ServerCallContext context) {
await foreach (var update in _updateSource.GetUpdatesAsync(context.CancellationToken)) {
await responseStream.WriteAsync(update);
}
}Real-world example A live dashboard subscribes to a server-streaming gRPC method that pushes stock price updates to the client as they occur in real time, rather than requiring the client to repeatedly poll a unary endpoint for the latest price.