Question

The typical Web API DelegatingHandler implementation looks like this...

protected async override Task<HttpResponseMessage> SendAsync(
    HttpRequestMessage request, CancellationToken cancellationToken)
{
    // TODO: Do work before inner handler here

    // Call the inner handler.
    var response = await base.SendAsync(request, cancellationToken);

    // TODO: Do work _after_ inner handler here

    return response;
}

What is the preferred method for dealing with CancellationToken.IsCancellationRequested == true?

Should I:

  • Generate an error response and break the delegate chain?
  • Do nothing (as above)?
  • Option 'C'?
Was it helpful?

Solution

Cancellation semantics are to throw an exception when the token is cancelled (e.g., CancellationToken.ThrowIfCancellationRequested).

If you don't have any asynchronous work to do (other than base.SendAsync), then you can just ignore the token.

Note that await base.SendAsync may raise an exception if the token is cancelled. The exception will propagate naturally, but if you have any cleanup that must take place regardless of cancellation, use a using or finally block.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top