The CancellationToken structure is used to propagate cancellation requests from one thread to others.
It allows a caller to signal that an operation should be canceled without canceling the thread itself.
Operations that support cancellation typically accept a CancellationToken parameter and periodically check its
IsCancellationRequested property or call the
ThrowIfCancellationRequested method.
When cancellation is requested, these operations should clean up any resources they are using and terminate.
Properties
| Name |
Description |
IsCancellationRequested |
Gets a value indicating whether a cancellation request has been made. |
| CanBeCanceled |
Gets a value indicating whether this token source can be canceled. |
Methods
| Name |
Description |
ThrowIfCancellationRequested |
Throws an OperationCanceledException if a cancellation request has been made. |
| Register(Action) |
Registers a delegate to be called when this token is canceled. |
| Register(Action<Object>, Object) |
Registers a delegate to be called when this token is canceled. |
| Equals(Object) |
Determines whether the specified object is equal to the current struct. |
| GetHashCode() |
Returns the hash code for the current struct. |
| ToString() |
Returns a string representation of the current struct. |
Operators
| Name |
Description |
| == |
Determines whether two CancellationToken instances are equal. |
| != |
Determines whether two CancellationToken instances are not equal. |
Fields
| Name |
Description |
| CancellationToken.None |
Gets a CancellationToken that is already in the canceled state. |
Example
using System;
using System.Threading;
using System.Threading.Tasks;
public class Example
{
public static async Task Main(string[] args)
{
var cts = new CancellationTokenSource();
var token = cts.Token;
Console.WriteLine("Starting a long-running operation...");
var task = Task.Run(() =>
{
try
{
for (int i = 0; i < 10; i++)
{
// Check for cancellation
if (token.IsCancellationRequested)
{
Console.WriteLine("Cancellation requested. Cleaning up...");
// Perform cleanup here
token.ThrowIfCancellationRequested(); // Throws OperationCanceledException
}
Console.WriteLine($"Operation progress: {i + 1}/10");
Thread.Sleep(500); // Simulate work
}
Console.WriteLine("Operation completed successfully.");
}
catch (OperationCanceledException)
{
Console.WriteLine("Operation was canceled.");
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
}, token); // Pass token to task
// Wait for a few seconds, then request cancellation
await Task.Delay(2500);
Console.WriteLine("Requesting cancellation...");
cts.Cancel();
// Wait for the task to finish
await task;
Console.WriteLine("Main method finished.");
}
}
Remarks
The CancellationToken struct is a lightweight value type that represents a cancellation token.
It is typically obtained from a CancellationTokenSource object.
When cancellation is requested from the source, all tokens obtained from it will signal that cancellation has been requested.
It is important to correctly handle cancellation requests in your asynchronous operations to ensure that resources are released and the application remains responsive.
The OperationCanceledException is the standard exception to throw when an operation is canceled via a CancellationToken.
Usage Scenarios
- Long-running background tasks that need to be stopped.
- Network requests that should be aborted if the user navigates away.
- UI operations that can be canceled if the user performs a different action.