What is a CancellationToken, and how do you use it properly?
Quick Answer
A CancellationToken is a cooperative signal that an operation should stop. Callers create a CancellationTokenSource, pass its Token down the async call chain, and callees either pass it to token-aware APIs or check token.ThrowIfCancellationRequested(). Cancellation is cooperative — nothing is forcibly aborted.
It's how you ask a running operation to stop early — a user navigated away, a timeout elapsed, the host is shutting down. The pattern is a CancellationTokenSource owns the source of truth and you thread its Token through every async call. Well-written APIs take a token and honour it; in your own loops you call ThrowIfCancellationRequested. It's cooperative, so if some code ignores the token it just keeps running. In ASP.NET Core I bind RequestAborted so that if the browser disconnects mid-request I stop hitting the database for a response nobody's waiting for.
- Always accept a
CancellationTokenparameter on async methods and forward it (toHttpClient, EF Core,Task.Delay, streams). - In ASP.NET Core,
HttpContext.RequestAbortedfires when the client disconnects — bind it as an action parameter to abandon abandoned work. CancellationTokenSource.CreateLinkedTokenSourcecombines a request token with a timeout.- A cancelled operation throws
OperationCanceledException/TaskCanceledException— usually let it propagate, don't swallow it as an error.