C#
CancellationToken
Learn to cancel a task with CancellationToken.
What is a CancellationToken?
CancellationToken is the standard way to cancel a long operation from outside. You create a CancellationTokenSource, get its Token, and pass it to the method. To cancel, call cts.Cancel();.
Inside the method you check with token.ThrowIfCancellationRequested() at each loop step. If cancellation was requested, OperationCanceledException is thrown. This is safer than killing a thread.
ThrowIfCancellationRequested
Inside a loop you call token.ThrowIfCancellationRequested() to check for cancellation. If cancellation was requested, this call immediately throws OperationCanceledException; otherwise it does nothing. So the call is cheap and can be made often.
A cancelled method typically throws OperationCanceledException; the caller catches it and treats cancellation as an expected outcome. Cancellation is not an error, it is an expected control flow.
Exercise Loop with CancellationToken
Define static async Task<int> CountAsync(CancellationToken token). In its body start with int sum = 0;; in a for (int i = 1; i <= 3; i++) loop on each step call token.ThrowIfCancellationRequested();, await Task.CompletedTask; and sum += i;; after the loop return sum;. Make Main a static async Task Main; create the source with var cts = new CancellationTokenSource();, call int total = await CountAsync(cts.Token); and print with Console.WriteLine(total);.
Show example solution
In CountAsync body start with int sum = 0;. In for (int i = 1; i <= 3; i++) loop write token.ThrowIfCancellationRequested(); await Task.CompletedTask; sum += i;. After the loop return sum;. Make Main static async Task Main() and write var cts = new CancellationTokenSource(); int total = await CountAsync(cts.Token); Console.WriteLine(total);
Example solution:
using System;
using System.Threading;
using System.Threading.Tasks;
class Program
{
static async Task<int> CountAsync(CancellationToken token)
{
int sum = 0;
for (int i = 1; i <= 3; i++)
{
token.ThrowIfCancellationRequested();
await Task.CompletedTask;
sum += i;
}
return sum;
}
static async Task Main()
{
var cts = new CancellationTokenSource();
int total = await CountAsync(cts.Token);
Console.WriteLine(total);
}
}
Test yourself
-
Create a CancellationTokenSource
var cts = new CancellationToken____();
Show answer
var cts = new CancellationTokenSource();
-
What is called to cancel?
- token.Cancel()
- cts.Cancelled = true
- cts.Stop()
- cts.Cancel()
Show answer
cts.Cancel() — Correct. cts.Cancel() triggers cancellation; the token then throws in ThrowIfCancellationRequested.
-
Match CancellationToken concepts
- CancellationTokenSource
- Cancellation source
- Token
- Control passed to method
- ThrowIfCancellationRequested
- Throws if cancelled
- cts.Cancel()
- Triggers cancellation
Next lesson: Summary - Task and ContinueWith