C# and .NET • Modern C# baseline
Cancellation Tokens and Responsive Operations
Propagate cancellation through async work and stop promptly at safe points.
CancellationToken communicates a cooperative request to stop; it does not forcibly terminate a method. Pass the token to supported APIs and check it in longer-running loops. Cleanup should still run when cancellation is observed.
Key points
- A cancelled operation commonly completes with OperationCanceledException.
- A token source owns cancellation and should be disposed when appropriate.
Example
static async Task DelayAsync(CancellationToken cancellationToken)
{
await Task.Delay(TimeSpan.FromSeconds(2), cancellationToken);
}
What to expect
Cancelling the token ends the delay early through the task’s cancellation path.
Practice exercise
Add a cancellation token to a loop that processes a large sequence and check it between batches.
Key idea: Cancellation is a request that all participating operations need to honor.