How to Use CancellationToken in C# for Task Cancellation
Use
CancellationToken in C# to signal cancellation requests to running tasks or async methods. Pass a CancellationToken to the method and check its IsCancellationRequested property or call ThrowIfCancellationRequested() to stop work gracefully.Syntax
The CancellationToken is usually obtained from a CancellationTokenSource. You pass the token to methods that support cancellation. Inside those methods, check if cancellation was requested and stop work if needed.
- CancellationTokenSource: Creates and controls the token.
- CancellationToken: Passed to tasks or async methods to observe cancellation.
- IsCancellationRequested: Property to check if cancellation was requested.
- ThrowIfCancellationRequested(): Throws an exception to stop the operation immediately.
csharp
var cts = new CancellationTokenSource(); CancellationToken token = cts.Token; // Pass token to a method SomeMethod(token); void SomeMethod(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { // Clean up and stop work return; } // Do work }
Example
This example shows how to start a task that counts numbers and supports cancellation. When the user presses a key, the cancellation is requested and the task stops gracefully.
csharp
using System; using System.Threading; using System.Threading.Tasks; class Program { static async Task Main() { var cts = new CancellationTokenSource(); CancellationToken token = cts.Token; Task countingTask = CountNumbersAsync(token); Console.WriteLine("Press any key to cancel..."); Console.ReadKey(true); cts.Cancel(); try { await countingTask; } catch (OperationCanceledException) { Console.WriteLine("Counting was canceled."); } } static async Task CountNumbersAsync(CancellationToken cancellationToken) { int count = 0; while (true) { cancellationToken.ThrowIfCancellationRequested(); Console.WriteLine(count++); await Task.Delay(500, cancellationToken); } } }
Output
Press any key to cancel...
0
1
2
3
... (numbers printed every 0.5 seconds until key press)
Counting was canceled.
Common Pitfalls
Common mistakes when using CancellationToken include:
- Not passing the token to all async methods or tasks that support cancellation.
- Failing to check
IsCancellationRequestedor callThrowIfCancellationRequested(), so the task never stops. - Ignoring
OperationCanceledExceptionwhich is thrown when cancellation is requested. - Calling
Cancel()on theCancellationTokenSourcetoo late or not at all.
Always handle cancellation exceptions and clean up resources properly.
csharp
/* Wrong way: ignoring cancellation token */ async Task DoWorkAsync() { while (true) { await Task.Delay(1000); // No cancellation token passed Console.WriteLine("Working..."); } } /* Right way: pass token and check cancellation */ async Task DoWorkAsync(CancellationToken token) { while (true) { token.ThrowIfCancellationRequested(); await Task.Delay(1000, token); Console.WriteLine("Working..."); } }
Quick Reference
CancellationToken Cheat Sheet:
| Term | Description |
|---|---|
| CancellationTokenSource | Creates and controls cancellation tokens. |
| CancellationToken | Passed to tasks/methods to observe cancellation. |
| IsCancellationRequested | True if cancellation was requested. |
| ThrowIfCancellationRequested() | Throws OperationCanceledException to stop work. |
| Cancel() | Method on CancellationTokenSource to request cancellation. |
| Term | Description |
|---|---|
| CancellationTokenSource | Creates and controls cancellation tokens. |
| CancellationToken | Passed to tasks/methods to observe cancellation. |
| IsCancellationRequested | True if cancellation was requested. |
| ThrowIfCancellationRequested() | Throws OperationCanceledException to stop work. |
| Cancel() | Method on CancellationTokenSource to request cancellation. |
Key Takeaways
Use CancellationTokenSource to create and control cancellation tokens.
Pass CancellationToken to async methods and check for cancellation regularly.
Call ThrowIfCancellationRequested() to stop work immediately when requested.
Handle OperationCanceledException to clean up after cancellation.
Always pass the token to all cancellable async operations to ensure proper cancellation.