CancellationToken
In this page:
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
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: