CancellationToken
A CancellationToken is a stop button you can pass to a long job, like a friend who can wave a flag to say 'please stop'. The job checks it and ends politely.
In this page:
Syntax
using var cts = new CancellationTokenSource();
cts.CancelAfter(milliseconds); // or cts.Cancel();
await Task.Delay(milliseconds, cts.Token); // throws OperationCanceledException
CancellationToken
CancellationToken provides a cooperative way to signal that a running asynchronous operation should stop early.
A CancellationTokenSource creates the token and can trigger cancellation with .Cancel(); the running code checks token.IsCancellationRequested or lets an awaited method throw OperationCanceledException. Cancellation is cooperative — the operation must actively check the token to actually stop.
Note:
Pass the same
CancellationToken down through every awaited call so cancellation propagates properly.Example: CancellationToken
using System;
using System.Threading;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
using var cts = new CancellationTokenSource();
cts.CancelAfter(50);
try
{
await Task.Delay(1000, cts.Token);
Console.WriteLine("Completed normally");
}
catch (OperationCanceledException)
{
Console.WriteLine("Operation was cancelled");
}
}
}
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Never passing the token to inner calls, so cancellation has no effect.
- Not checking
IsCancellationRequestedin long loops. - Forgetting to catch
OperationCanceledException.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: