Represents the mechanism by which a CancellationToken is created and signaled.
The CancellationTokenSource
class is used to create a CancellationToken
that can be passed to operations that should be canceled. The CancellationTokenSource
then provides a way to signal that cancellation has been requested. This is a fundamental component for cooperative cancellation in asynchronous operations and multithreaded applications.
Key functionalities include:
CancellationToken
.Public static members of this type are thread-safe. Any instance members are not guaranteed to be thread-safe.
When a CancellationToken
is passed to an operation, that operation should periodically check the IsCancellationRequested
property of the token. If it becomes true, the operation should clean up its resources and terminate. The operation can also register callbacks to be executed when cancellation is requested.
The Dispose()
method should be called when the CancellationTokenSource
is no longer needed to release any unmanaged resources.
You can configure a CancellationTokenSource
to automatically cancel after a specified time interval using the CancelAfter()
method or the constructor overloads that accept a delay.
You can link multiple CancellationTokenSource
instances together. When one source is canceled, it can trigger the cancellation of others.
CancellationTokenSource
class.millisecondsDelay
)CancellationTokenSource
class and sets the delay before cancellation.TimeSpan
delay
)CancellationTokenSource
class and sets the delay before cancellation.CancellationToken
{ get
; }CancellationToken
associated with this CancellationTokenSource
instance.bool
{ get
; }bool
throwOnFirstException
)throwOnFirstException
is true, and an exception occurs during cancellation, the first exception will be thrown.int
millisecondsDelay
)TimeSpan
delay
)CancellationTokenSource
class.params
CancellationToken
[] tokens
)CancellationTokenSource
that will be canceled when any of the supplied tokens is canceled.params
CancellationToken
[] tokens
)CancellationTokenSource
that will be canceled when any of the supplied tokens is canceled or after the specified delay.bool
disposing
)CancellationTokenSource
and optionally releases the managed resources.This example demonstrates how to use CancellationTokenSource
to cancel a long-running operation.
using System;
using System.Threading;
using System.Threading.Tasks;
public class Example
{
public static async Task Main(string[] args)
{
// Create a CancellationTokenSource
var cts = new CancellationTokenSource();
CancellationToken token = cts.Token;
Console.WriteLine("Starting a long-running operation...");
// Start a task that can be cancelled
var longRunningTask = Task.Run(() =>
{
try
{
for (int i = 0; i < 10; i++)
{
// Check if cancellation has been requested
token.ThrowIfCancellationRequested();
Console.WriteLine($"Operation step {i}...");
Thread.Sleep(500); // Simulate work
}
Console.WriteLine("Long-running operation completed successfully.");
}
catch (OperationCanceledException)
{
Console.WriteLine("Operation was cancelled.");
}
}, token);
// Wait for a moment, then request cancellation
await Task.Delay(2000);
Console.WriteLine("Requesting cancellation...");
cts.Cancel();
// Wait for the task to complete (either by finishing or being cancelled)
await longRunningTask;
// Clean up the CancellationTokenSource
cts.Dispose();
Console.WriteLine("Program finished.");
}
}
This example shows how to use CancelAfter
to automatically cancel an operation after a specified time.
using System;
using System.Threading;
using System.Threading.Tasks;
public class ExampleWithDelay
{
public static async Task Main(string[] args)
{
// Create a CancellationTokenSource that will cancel after 3 seconds
var cts = new CancellationTokenSource();
Console.WriteLine("Starting an operation that will be auto-cancelled in 3 seconds...");
var operation = Task.Run(async () =>
{
try
{
cts.CancelAfter(3000); // Cancel after 3000 milliseconds
for (int i = 0; i < 10; i++)
{
if (cts.Token.IsCancellationRequested)
{
Console.WriteLine("Cancellation detected within loop.");
break;
}
Console.WriteLine($"Working... {i}");
await Task.Delay(1000, cts.Token); // Important: pass token to delay too
}
Console.WriteLine("Operation finished before auto-cancellation.");
}
catch (OperationCanceledException)
{
Console.WriteLine("Operation was cancelled by timer.");
}
});
await operation;
cts.Dispose();
Console.WriteLine("Program finished.");
}
}