What is a CancellationToken, and how do you use it properly?

C# Async & Concurrency Intermediate 2–3 Yrs3–5 Yrs Conceptual 1 min read

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 CancellationToken parameter on async methods and forward it (to HttpClient, EF Core, Task.Delay, streams).
  • In ASP.NET Core, HttpContext.RequestAborted fires when the client disconnects — bind it as an action parameter to abandon abandoned work.
  • CancellationTokenSource.CreateLinkedTokenSource combines a request token with a timeout.
  • A cancelled operation throws OperationCanceledException / TaskCanceledException — usually let it propagate, don't swallow it as an error.