Asking work to stop
Long running async work sometimes becomes unwanted. The user navigates away, a timeout elapses, or a faster result already arrived. A cancellation token is a small object the caller can flip to a cancelled state, and that running work watches to decide when to stop early.
Cooperative by nature
A token does not forcibly kill anything. Cancellation is cooperative, meaning the running code must check the token and respond.
- The work polls the token at safe points, or
- it registers a callback to fire when cancellation is requested, or
- an awaited operation throws a cancellation error when the token trips.
Code that never checks the token simply keeps running, so good libraries check often and unwind cleanly.
Propagating cancellation
One token usually flows down through a whole call chain. When the top is cancelled, every operation sharing the token observes it.
- Pass the same token into nested calls.
- Release resources like connections and files on cancellation.
- Distinguish a cancellation from an ordinary error so callers react correctly.
Key idea
A cancellation token is a shared signal the caller flips and cooperative work checks, letting long operations stop early, release resources, and report cancellation distinctly from failure.