×

c# · level 3 · unit 6 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. 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.