What is a CancellationToken and how do you use it?

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

Quick Answer

A CancellationToken is a cooperative cancellation signal. A CancellationTokenSource creates and controls it; you pass the token into async/long-running methods, which check token.ThrowIfCancellationRequested() or pass it further down. Cancelling throws OperationCanceledException at the next check.

A CancellationToken is how you ask an operation to stop. Something creates a CancellationTokenSource and hands out its token, and you thread that token through every async call — the HTTP client, the EF query, Task.Delay. It's cooperative: the token doesn't kill anything, the code has to check it and throw. In an ASP.NET Core action I take a CancellationToken parameter, which the framework wires to the request being aborted, so if the user closes the tab I stop hitting the database. And I use a linked token source to combine that with a timeout.

  • Cancellation is cooperative — the token doesn't stop anything by force; the code has to observe it. Pass it all the way down to HttpClient, EF queries, Task.Delay, streams.
  • ASP.NET Core gives you HttpContext.RequestAborted — bind it as an action parameter so a query is abandoned when the client disconnects.
  • CancellationTokenSource(TimeSpan) for a timeout; CreateLinkedTokenSource to combine a caller's token with a timeout.
  • Catch OperationCanceledException separately from real errors — a cancellation is usually not a failure to log as an error.