liveBook · Manning

CancellationToken

As explained in C# Concurrency: Asynchronous and multithreaded programming

A CancellationToken is a .NET value that communicates a request to cancel an asynchronous or otherwise cancellable operation.

CancellationToken is .NET’s standard signal for requesting that an asynchronous or otherwise cancellable operation stop. A CancellationTokenSource creates and controls the token; the operation receives only the token and checks IsCancellationRequested. section 9.0 section 9.1

The token does not forcibly terminate work: it is essentially a thread-safe cancellation flag. Cancellation happens only when the operation checks the token or passes it to a cancellable API. Long-running work should check periodically; otherwise cancellation waits for the current operation to finish. section 9.1

A practical cancellation flow is:

  • Create a CancellationTokenSource and pass its Token to the background or asynchronous operation. section 9.1
  • Request cancellation with CancellationTokenSource.Cancel rather than attempting to stop the operation externally. section 9.7
  • Check IsCancellationRequested inside loops and long-running calculations, or pass the token to APIs that support cancellation. section 9.1 section 14.3
  • Use Register for cancellation callbacks, CancelAfter for timeouts, linked token sources for combined requests, and CancellationToken.None when cancellation is not wanted. section 9.7

Canceling a long-running calculation

A worker can return when cancellation is observed inside its expensive calculation: bool ACalculationThatTakesOneMinute(CancellationToken token) { while (...) { if (token.IsCancellationRequested) return false; result++; } return true; }. The caller stops processing when the method returns false. section 9.1

Listing 9.6 Using CancellationToken
var thread = new Thread(BackgroundProc);
var cancelTokenSource = new CancellationTokenSource();     #1
var shouldCancel = cancelTokenSource.Token;                #2
thread.Start();
Console.ReadKey();
cancelTokenSource.Cancel();                                #3
 
void BackgroundProc()
{
   int i=0;
   while(true)
   {
      if(shouldCancel. IsCancellationRequested) return;    #4
      Console.WriteLine(i++);
   }
}

Use the complete listing to compare the source-controlled token with the worker’s read-only cancellation checks. section 9.1

Listing 14.5 Async yield return example with cancellation
private async IAsyncEnumerable<int> AsyncYieldDemo( 
   [EnumeratorCancellation] CancellationToken cancellationToken = default) #1
{
   yield return 1;
   await Task.Delay(1000, cancellationToken);
   yield return 2;
}
 
public async Task UseAsyncYieldDemo()
{
   var cancel = new CancellationTokenSource();
   var collection = AsyncYieldDemo();
   await foreach(var current in 
        collection.WithCancellation(cancel.Token))                         #2
   {
         Console.WriteLine($"Got {current}");
   }
}

Use the asynchronous-stream example to see a token passed through WithCancellation and received by an async iterator. section 14.3

How C# Concurrency: Asynchronous and multithreaded programming covers it

How deep it goes
Explains source-token separation, polling, delayed cancellation, callbacks, timeouts, linked sources, and async-iterator propagation.
Examples
Demonstrates cancelable background loops, long calculations, Task.Delay, async iterators, and await foreach with WithCancellation.
What it assumes
Assumes basic C# threads and asynchronous iteration while building cancellation from a shared flag and its synchronization concerns.
What you can do after
Apply it via .NET APIs to design cooperative cancellation and propagate requests through long-running and asynchronous workflows.
How it connects
Connects CancellationTokenSource, background threads, asynchronous operations, IAsyncEnumerable, await foreach, timeouts, and callbacks.

Also explained in

Compare how 2 books explain CancellationToken →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of C# Concurrency: Asynchronous and multithreaded programming. The section links point to the parts of the book it draws on.