1

I'm working on a gRPC client that continuously streams data (such as images) from a server. I use a CancellationToken to stop the stream when needed. While cancellation works, I consistently see exceptions being thrown — even in what I believe are normal, graceful cancellation scenarios.

These include: RpcException with StatusCode.Cancelled – expected and handled But also (occasionally or consistently): ObjectDisposedException InvalidOperationException RpcException with StatusCode.Unavailable

I'm trying to implement cancellation in a way that avoids these non-cancellation exceptions, and wondering if there's a better pattern or API usage for this scenario.

Code Example:

public static class ExceptionUtils
{
    public static bool IsCancellation(Exception ex)
    {
        return ex is RpcException rpc && rpc.StatusCode == StatusCode.Cancelled;
    }
}

void StartStream()
{
    _cts = new CancellationTokenSource();
    _streamTask = Task.Run(() =>
    {
        try
        {
            StreamLoop(_imageQueue, _cts.Token);
        }
        catch (Exception ex) when (ExceptionUtils.IsCancellation(ex))
        {
            _log.Info("Stream cancelled gracefully");
        }
    });
}

void StopStream()
{
    _cts.Cancel();
    _streamTask?.Wait();
    _streamTask?.Dispose();
}

void StreamLoop(BlockingCollection<ImageData> queue, CancellationToken ct)
{
    var stream = _grpcClient.StreamData(new Empty());`enter code here`
    try
    {
        while (stream.ResponseStream.MoveNext(ct).Result)
        {
            var current = stream.ResponseStream.Current;
            queue.Add(current);
        }
    }
    finally
    {
        stream?.Dispose();
    }
}

Questions:

  1. How can I cancel a gRPC client streaming call cleanly, such that: Only a RpcException(StatusCode.Cancelled) is raised at most — or ideally no exception at all?

  2. What’s the correct pattern to ensure I don’t get: ObjectDisposedException InvalidOperationException RpcException(StatusCode.Unavailable)

  3. Is the Dispose() of the stream in the right place?

  4. Is there any best practice or mechanism in Grpc.Net.Client that ensures clean cancellation without triggering these runtime exceptions?

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.