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

