Back to results for “Exception Handling”
C# › Asynchronous Programming

How does CancellationToken propagate cancellation requests through a chain of async method calls?

Advanced

Answer

A CancellationTokenSource creates a CancellationToken that's passed down through every async method in the call chain; any method (or an awaited library call like HttpClient or Task.Delay) that receives the token can periodically check token.IsCancellationRequested or call token.ThrowIfCancellationRequested(), and calling source.Cancel() propagates the signal to every consumer holding that same token.
async Task ProcessAsync(CancellationToken token) {
  for (int i = 0; i < 1000000; i++) {
    token.ThrowIfCancellationRequested(); // cooperative cancellation check
    await DoWorkAsync(i, token); // token passed further down the chain
  }
}

var cts = new CancellationTokenSource();
cts.CancelAfter(TimeSpan.FromSeconds(5));
await ProcessAsync(cts.Token);
Real-world example Cancelling a long-running batch operation or API request when a user navigates away or a timeout is reached.

Common follow-ups: What exception type is thrown when ThrowIfCancellationRequested() detects cancellation, and how should it typically be handled?