Cancellation
A long operation needs a way to stop when the caller no longer wants the result: a request timed out, a user closed the window, a service is shutting down. .NET passes a CancellationToken through the call, and the callee decides where it looks at it. This is cooperative cancellation: nothing is killed from outside.
A token and a source
A CancellationTokenSource owns the signal, and its Token is the read-only struct that the callee receives. The program gives the token to a loop, waits until the loop has printed its first line, and then cancels:
using var source = new CancellationTokenSource();
var token = source.Token;
var started = new TaskCompletionSource();
var task = Count(token, started);
await started.Task;
source.Cancel();
try
{
await task;
}
catch (OperationCanceledException)
{
Console.WriteLine("cancelled");
}
Console.WriteLine($"status {task.Status}");
Console.WriteLine($"token {token.IsCancellationRequested}");
static async Task Count(CancellationToken token, TaskCompletionSource started)
{
token.ThrowIfCancellationRequested();
Console.WriteLine("tick 1");
started.SetResult();
await Task.Delay(10, token);
Console.WriteLine("tick 2");
}
dotnet run
tick 1
cancelled
status Canceled
token True
The first tick printed, the signal arrived while the method waited, and Task.Delay(10, token) stopped with an OperationCanceledException instead of waiting the rest of the ten milliseconds. The task is Canceled, not faulted, which is the difference between "somebody asked to stop" and "something went wrong". The second tick never printed.
Cancellation is cooperative
Cancelling a source only sets a flag. A method that never reads the token runs to its end, and the task finishes normally; the caller that awaits it does not know the cancellation was too late. The places a method looks at the token are its own decision:
- Before a unit of work, with ThrowIfCancellationRequested.
- In a wait, by passing the token to Task.Delay or to the buffered read that accepts one.
- In a loop, once per iteration, so that the stop is quick without checking after every statement.
- In the catch of a library, never: a library that swallows an OperationCanceledException hides the stop from its caller.
A method that stops because of its token should throw rather than return a default value, so that the caller sees the cancellation in the task status. The exception type is OperationCanceledException or its derived TaskCanceledException, and both are caught by the type of the first one.
CancelAfter and the timeout
A source can cancel itself after a time, which is how a timeout is built without a second thread:
var none = CancellationToken.None;
Console.WriteLine($"none can be cancelled {none.CanBeCanceled}");
using var source = new CancellationTokenSource();
source.CancelAfter(TimeSpan.FromSeconds(5));
Console.WriteLine($"scheduled {!source.IsCancellationRequested}");
Console.WriteLine($"can be cancelled {source.Token.CanBeCanceled}");
source.Cancel();
Console.WriteLine($"now {source.IsCancellationRequested}");
Console.WriteLine($"throw {Throws(source.Token)}");
static bool Throws(CancellationToken token)
{
try
{
token.ThrowIfCancellationRequested();
return false;
}
catch (OperationCanceledException)
{
return true;
}
}
dotnet run
none can be cancelled False
scheduled True
can be cancelled True
now True
throw True
CancellationToken.None is the token that can never be cancelled, and it is the default of an optional parameter. CancelAfter schedules the signal; the program cancelled at once, so the run did not wait five seconds, and the flag was true before the timer would have fired. A real timeout passes the token to the work and treats the resulting cancellation as a timeout of its own, with a message that says which deadline passed.
The status of a cancelled task
A task that ends through its token is Canceled, a task that throws another exception is Faulted, and the two are read differently. A caller that treats a cancellation as an error logs a warning for a normal shutdown. The lesson on locks and the capstones use this rule: a worker stopped by the stop signal is not a failure, and the summary counts it as one that finished.
Exercises
- Remove the token from Task.Delay and cancel during the wait; what does the task print?
- Give a method a timeout of ten milliseconds with CancelAfter and make it work for a hundred.
- Catch TaskCanceledException instead of OperationCanceledException and see which one the runtime throws.
- Link two sources with CreateLinkedTokenSource and cancel one of them.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does a CancellationTokenSource do?
Answer
It owns the signal and hands out the token that the callee reads
The source cancels and the token is the read-only view passed down the call.
-
What does ThrowIfCancellationRequested do?
Answer
Throws OperationCanceledException when the token is cancelled
It is the check that turns the flag into the exception of a cancelled task.
-
What does this program print?
var source = new CancellationTokenSource(); source.Cancel(); Console.WriteLine(source.Token.IsCancellationRequested);Answer
True
Cancel sets the flag that the token reports.
-
What does CancellationToken.None.CanBeCanceled give?
Answer
False
None is the token that can never be cancelled, as the measured line showed.
-
What does this program print?
Console.WriteLine(CancellationToken.None.CanBeCanceled);Answer
False
The none token has no source behind it, so it can never be cancelled.
-
What does CancelAfter do?
Answer
Schedules the cancellation for a moment in the future
The source cancels itself after the delay, which is a timeout.
-
Which status has a task that stopped through its token?
Answer
Canceled
The measured task was Canceled, which is not the same as a failure.
-
What does this program print?
Console.WriteLine(new CancellationTokenSource().Token.CanBeCanceled);Answer
True
A source with no cancellation yet still hands out a token that can be cancelled.
-
Why is cancellation cooperative?
Answer
The callee must check the token at a point it chooses
Nothing is killed from outside; a method that ignores the token runs to its end.
-
What does this program print?
var source = new CancellationTokenSource(); source.Cancel(); try { source.Token.ThrowIfCancellationRequested(); } catch (OperationCanceledException) { Console.WriteLine("stopped"); }Answer
stopped
The check throws and the catch prints its line.
The code on this page was built with the .NET SDK 10.0.303 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev