c# · level 3 · unit 6 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A lets you stop work politely.
Users close pages and time limits run out, so work in flight must be able to stop. C# does this by agreement. A CancellationTokenSource is the remote control. Its Token, a cancellation token, goes to every piece of work that should listen.
Calling Cancel(), or CancelAfter(ms), flips the token. Work checks in at safe points with token.ThrowIfCancellationRequested(), which throws once cancelling has begun. Waits such as Task.Delay(ms, token) listen by themselves. Catch the exception where you started the work.
using System;
using System.Threading;
using System.Threading.Tasks;
var remote = new CancellationTokenSource();
remote.CancelAfter(150);
try
{
await WatchQueueAsync(remote.Token);
}
catch (OperationCanceledException)
{
Console.WriteLine("Stopped watching: time is up");
}
async Task WatchQueueAsync(CancellationToken token)
{
while (true)
{
token.ThrowIfCancellationRequested();
await Task.Delay(40, token);
}
} Nothing here prints how many checks ran, because that depends on timing.
guess first
Cancelled before it starts. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
using System;
using System.Threading;
using System.Threading.Tasks;
var remote = new CancellationTokenSource();
remote.Cancel();
try
{
await PrintAsync(remote.Token);
}
catch (OperationCanceledException)
{
Console.WriteLine("cancelled");
}
async Task PrintAsync(CancellationToken token)
{
Console.WriteLine("starting");
await Task.Delay(10);
token.ThrowIfCancellationRequested();
Console.WriteLine("printing");
}
your turn
Your turn. Give up on a slow report.
On line 19, hand the token to Task.Delay, so the long wait listens for cancelling. Then write your own message on line 14.
output
press run to see what happens
fix it
The export ignores the time limit. Can you fix it?
output
press run to see what happens
- The export should stop after 100 ms, but it finishes all 5 pages. Does anything look at the token?
ExportAsyncis handed the token but never checks it, so cancelling has no effect.- Add
token.ThrowIfCancellationRequested();as the first line inside the loop, then run.
nailed it
your work can stop when asked. :D
- A
CancellationTokenSourcemakes a token and cancels it. - Work must check the token or pass it on.
- Catch
OperationCanceledExceptionwhere you started the work.
new words in your collection
- cancellation token
- OperationCanceledException
This lesson isn’t saved. A free account remembers every lesson you finish.