You can't safely kill a running task from outside: it might be halfway through a change. .NET's cancellation is cooperative: someone requests a stop, and the work checks for the request and stops at a safe point. The two types are CancellationTokenSource, held by whoever decides, and CancellationToken, handed to whoever works.
Requesting and observing
Pass a token down, and async library methods such as Task.Delay will observe it for you. They end by throwing an OperationCanceledException, or its subclass TaskCanceledException. Always catch the base class. In a CPU loop, call ThrowIfCancellationRequested from time to time.
using var source = new CancellationTokenSource();
Task work = WorkAsync(source.Token);
source.Cancel();
try
{
await work;
}
catch (OperationCanceledException)
{
Console.WriteLine("cancelled");
}
Console.WriteLine(work.IsCanceled);
static async Task WorkAsync(CancellationToken token)
{
Console.WriteLine("started");
await Task.Delay(5000, token);
Console.WriteLine("never printed");
}Check your prediction
started
cancelled
TrueTimeouts are cancellation
CancellationTokenSource(ms), or CancelAfter, requests cancellation after a delay. WaitAsync(timeout) puts a limit on any task, and it throws TimeoutException. Note that it doesn't stop the underlying work. It only stops waiting for it. Only a token can ask the work to stop.
using var source = new CancellationTokenSource(20);
try
{
await Task.Delay(5000, source.Token);
}
catch (OperationCanceledException)
{
Console.WriteLine("token timed out");
}
Task slow = Task.Delay(50);
try
{
await slow.WaitAsync(TimeSpan.FromMilliseconds(5));
}
catch (TimeoutException)
{
Console.WriteLine("stopped waiting");
}
Console.WriteLine(slow.IsCompleted);
await slow;
Console.WriteLine(slow.IsCompleted);Check your prediction
token timed out
stopped waiting
False
TrueLinked sources
Most real calls have two reasons to stop: the caller wants out, and this one attempt took too long. CreateLinkedTokenSource makes a source that's cancelled if any of its parents is, and it can have its own timeout. The when filters below are the exact pattern the job runner uses to tell the two apart. Order matters, since both flags are true if the caller cancelled.
Console.WriteLine(await RunAsync(5000, 20, CancellationToken.None));
using (var caller = new CancellationTokenSource(10))
{
Console.WriteLine(await RunAsync(5000, 2000, caller.Token));
}
Console.WriteLine(await RunAsync(1, 2000, CancellationToken.None));
static async Task<string> RunAsync(int workMs, int timeoutMs, CancellationToken token)
{
using var attempt = CancellationTokenSource.CreateLinkedTokenSource(token);
attempt.CancelAfter(timeoutMs);
try
{
await Task.Delay(workMs, attempt.Token);
return "finished";
}
catch (OperationCanceledException) when (token.IsCancellationRequested)
{
return "cancelled by caller";
}
catch (OperationCanceledException) when (attempt.IsCancellationRequested)
{
return "timed out";
}
}Check your prediction
timed out
cancelled by caller
finishedDispose linked sources, as they register with their parents and would otherwise stay alive. The using does that.
Good habits
- Accept a
CancellationTokenas the last parameter of an async method that can take a while, and pass it to everything you call. - Don't catch
OperationCanceledExceptionunless you can do something useful, and then let it go on. A method that stops early should not look as if it succeeded. - Clean up with
finallyorusing, since cancellation arrives as an exception. - Never use the token you were given for cleanup work. It's already been cancelled, so the cleanup would stop at once.
CPU work checks for itself
A loop that never awaits never notices a token unless it checks. In this browser, there's a further catch: with one thread, a tight loop stops timers from firing at all, so a Cancel scheduled for later never gets its turn. Even Task.Yield isn't enough here, since it lets waiting code continue but doesn't always let a timer fire. A short Task.Delay does. On a multi-core machine, a loop like this needs no delay, because the timer runs on another thread.
using var source = new CancellationTokenSource();
int done = 0;
Task loop = LoopAsync();
await Task.Delay(1);
source.Cancel();
try
{
await loop;
}
catch (OperationCanceledException)
{
Console.WriteLine("stopped");
}
Console.WriteLine(done < 1_000_000);
async Task LoopAsync()
{
for (int i = 0; i < 1_000_000; i++)
{
source.Token.ThrowIfCancellationRequested();
done = i;
if (i % 100 == 0)
{
await Task.Delay(1);
}
}
}Check your prediction
stopped
TrueYour turn
First response wins
Write FirstAsync(Func<CancellationToken, Task<string>>[] sources, CancellationToken token). It starts all sources at once with a linked token, returns the first successful result, and cancels the others. If every source fails, throw InvalidOperationException with the text all sources failed. If the caller cancels, let the OperationCanceledException reach them.
Fake sources are lambdas that take a token and call Task.Delay(ms, token). Test three cases: a fast failure and a slower success, which returns the success; two failures; and caller cancellation on a slow source. Also show that the losing source saw the cancellation, with a counter.
When it works, it prints:
second
1
all sources failed
caller cancelledusing var source = new CancellationTokenSource(10);
await Task.Delay(1, source.Token);
Console.WriteLine("Start here");Hint 1: the idea
Keep a list of unfinished tasks. Loop on WhenAny, removing the winner each time. If it succeeded, cancel the rest and return; if it failed, keep going.
Hint 2: a first step
Check the caller's token after each WhenAny, using token.ThrowIfCancellationRequested(). Inspect the finished task with IsCompletedSuccessfully rather than a try.
Show one solution
int cancelledLosers = 0;
async Task<string> Slow(int ms, string value, CancellationToken token)
{
try
{
await Task.Delay(ms, token);
return value;
}
catch (OperationCanceledException)
{
cancelledLosers++;
throw;
}
}
async Task<string> Fails(int ms, CancellationToken token)
{
await Task.Delay(ms, token);
throw new IOException("no answer");
}
Console.WriteLine(await FirstAsync(new Func<CancellationToken, Task<string>>[]
{
token => Fails(1, token),
token => Slow(10, "second", token),
token => Slow(5000, "third", token),
}, CancellationToken.None));
await Task.Delay(1);
Console.WriteLine(cancelledLosers);
try
{
await FirstAsync(new Func<CancellationToken, Task<string>>[] { token => Fails(1, token), token => Fails(2, token) }, CancellationToken.None);
}
catch (InvalidOperationException e)
{
Console.WriteLine(e.Message);
}
using var caller = new CancellationTokenSource(5);
try
{
await FirstAsync(new Func<CancellationToken, Task<string>>[] { token => Slow(5000, "late", token) }, caller.Token);
}
catch (OperationCanceledException)
{
Console.WriteLine("caller cancelled");
}
static async Task<string> FirstAsync(Func<CancellationToken, Task<string>>[] sources, CancellationToken token)
{
using var linked = CancellationTokenSource.CreateLinkedTokenSource(token);
List<Task<string>> pending = sources.Select(source => source(linked.Token)).ToList();
while (pending.Count > 0)
{
Task<string> finished = await Task.WhenAny(pending);
pending.Remove(finished);
token.ThrowIfCancellationRequested();
if (finished.IsCompletedSuccessfully)
{
linked.Cancel();
return await finished;
}
}
throw new InvalidOperationException("all sources failed");
}second
1
all sources failed
caller cancelledCompletion is saved in this browser only. It does not measure mastery.