In C#, what is the difference between a CancellationTokenSource and a CancellationToken, and how does a cancel request reach an async method?
answer
- sender and receiver
- one class, one readonly struct
- Cancel lives on only one of them
- last parameter, forwarded to every call
basics
~20 sA CancellationTokenSource sends the request: Cancel, CancelAfter and Dispose live on it. A CancellationToken is the read-only struct that code receives to observe it. Each async method takes the token and forwards it to every call that accepts one.
solid answer
~40 sThe two types split the job. `CancellationTokenSource` is a class owned by whoever decides to stop the work, such as a Cancel button handler: it has `Cancel()`, `CancelAfter()` and `Dispose()`, and its `Token` property hands out a `CancellationToken`. The token is a `readonly struct` that can only observe: `IsCancellationRequested`, `ThrowIfCancellationRequested()`, `Register()` and `CanBeCanceled`. Code that receives a token cannot cancel anyone else's work. In an async call chain each method takes a `CancellationToken cancellationToken = default` as its last parameter and passes it to every awaited call that accepts one, such as `Task.Delay` or a stream's `ReadAsync`. Cancellation is cooperative: nothing stops code that never looks at the token.
code
csharp · 29 linesusing var cts = new CancellationTokenSource();
Task import = ImportAllAsync(["a.csv", "b.csv", "c.csv"], cts.Token);
await Task.Delay(150); // the user clicks Cancel while b.csv is in progress
cts.Cancel();
try
{
await import;
}
catch (OperationCanceledException)
{
Console.WriteLine("Import cancelled");
}
static async Task ImportAllAsync(string[] files, CancellationToken cancellationToken)
{
foreach (var file in files)
{
cancellationToken.ThrowIfCancellationRequested();
await ImportFileAsync(file, cancellationToken);
Console.WriteLine($"{file} imported");
}
}
static async Task ImportFileAsync(string file, CancellationToken cancellationToken)
{
await Task.Delay(100, cancellationToken); // stands in for reading and saving the file
}go deeper
Recall which type has Cancel and which one methods take as a parameter, and show the token forwarded to every awaited call.
Explain why cooperative cancellation means a method that never checks or forwards the token cannot be stopped, and where checkpoints belong in a loop.
Show how you audit a call chain for a dropped token, using CA2016 and CA1068, and who owns and disposes each source.
Weigh where a codebase draws the line between cancellable calls and calls that must finish, and how that rule is reviewed across teams.
## Two types, two roles .NET splits cancellation into a **sender** and a **receiver** so that the code doing the work can never cancel itself by accident, and the code that decides to stop does not need to know how the work is done. | | `CancellationTokenSource` | `CancellationToken` | |---|---|---| | Kind | class, implements `IDisposable` | `readonly struct` | | Who holds it | the owner of the decision (a Cancel button, a timeout, a parent operation) | every method that does cancellable work | | Can request cancellation | yes: `Cancel()`, `CancelAfter()`, the `CancellationTokenSource(TimeSpan)` constructor | no | | Can observe it | `IsCancellationRequested` | `IsCancellationRequested`, `ThrowIfCancellationRequested()`, `Register()`, `WaitHandle` | The source's `Token` property returns a token bound to that source. Many tokens can be handed out from one source, and they all report the same state. A `CancellationToken` is a small struct that wraps a reference to its source, so copying it is cheap and every copy sees the same request. ## How a request travels In the file-import job, the window owns a `CancellationTokenSource` and the Cancel button calls `Cancel()` on it. The import method never sees the source, only its token: 1. The window creates the source and calls `ImportAllAsync(files, cts.Token)`. 2. `ImportAllAsync` takes `CancellationToken cancellationToken` and passes it to `ImportFileAsync` for each file. 3. `ImportFileAsync` passes it again to the calls that actually wait: `Task.Delay`, `Stream.ReadAsync`, `HttpClient.GetAsync`, a database driver's async methods. 4. When the user clicks Cancel, `Cancel()` sets the source's state, and every token from it now reports `IsCancellationRequested == true`. 5. Whichever call is waiting at that moment notices, stops, and throws `OperationCanceledException` (or its subclass `TaskCanceledException`), which travels back up through each `await`. Nothing in this chain is automatic. **Cancellation is cooperative**: the token is a flag plus a notification mechanism, and only code that checks the flag or passes the token on will stop. A loop that never calls `ThrowIfCancellationRequested()`, or an awaited method called without the token, keeps running after Cancel. ## Conventions that keep the chain intact - **The parameter goes last** and is usually named `cancellationToken`, with `= default` on public APIs so callers can omit it. Code analysis rule **CA1068** ("CancellationToken parameters must come last") checks the position. - **Forward it to every call that accepts one.** Rule **CA2016** ("Forward the CancellationToken parameter to methods that take one") flags calls that could take the token but do not. In .NET 10 both rules are enabled by default only as suggestions, so they show in the IDE rather than failing a build. - **`default` and `CancellationToken.None` are the same value**: a token with no source, whose `CanBeCanceled` is `false`. Passing it means "this call cannot be cancelled", which is fine for a call that must finish but wrong as a lazy default deep inside a cancellable operation. - **Check at checkpoints in CPU-bound loops.** A loop that parses rows should call `cancellationToken.ThrowIfCancellationRequested()` every so often, before work that has side effects. - **Do not pass the source around.** Handing a `CancellationTokenSource` to a callee gives it the power to cancel the caller's other work and to dispose a source it does not own. ## The source's own lifetime A `CancellationTokenSource` implements `IDisposable`, and Microsoft's documentation asks you to call `Dispose()` when you have finished with it. After disposal, reading its `Token` property or calling `Cancel()` or `CancelAfter()` throws `ObjectDisposedException`, so the owner disposes it only once the work that uses its token has finished. A source created for one import run belongs in a `using` declaration in the method that owns that run. Tokens already handed out keep working as values after the source is disposed, but they can no longer be cancelled through it. ## Where this leaf stops Timeouts and combining the Cancel button with a deadline, how the cancelled task reports its outcome, `Register` callbacks and `Task.WaitAsync` each have their own question. The tokens a web host passes for an aborted request or for application shutdown are covered with ASP.NET Core, and passing a token into an `IAsyncEnumerable<T>` is covered with asynchronous sequences. Why cancellation is cooperative in every modern runtime, rather than a forced stop, is covered in the concurrency foundations.
- In C#, why is CancellationToken a struct while CancellationTokenSource is a class?The source owns mutable shared state: the cancelled flag, registered callbacks and an optional timer, so it must be one object that everyone references. The token is only a handle to that source, a single reference wrapped in a `readonly struct`, so passing it by value through every call costs nothing extra and every copy still points at the same source. `default(CancellationToken)` simply has no source and can never be cancelled.
- In a C# async method, what happens if one awaited call in the chain is made without forwarding the CancellationToken?That call cannot be interrupted. When the user cancels while it is running, it runs to completion, and the method only notices at its next check of the token, if there is one. If that call is the slow one, such as a large download, Cancel appears to do nothing for its whole duration. Code analysis rule CA2016 points out such calls when an overload with a token exists.
A building's fire alarm panel and its bells: only the panel can set the alarm off, every room has a bell that rings when it does, and the people in each room still have to walk out themselves; the bell carries nobody.
- Passes the CancellationTokenSource itself down the call chain instead of its token
- Believes calling Cancel() stops the running code even if it never checks the token
- Calls async APIs without forwarding the token because the method's own loop checks it
- Thinks CancellationToken.None is a token that is already cancelled
- Disposes the source while work using its token is still running