CancellationToken Struct
Summary
Represents an operation that can be cancelled. This type is used to propagate cancellation signals across asynchronous operations.
public struct CancellationToken
A CancellationToken
is a struct that represents an operation that can be cancelled. It is passed to asynchronous operations to signal that they should stop their work. The CancellationTokenSource
class is used to create and manage the cancellation token and to trigger the cancellation signal.
When a CancellationToken
is passed to an operation, that operation can periodically check the IsCancellationRequested
property. If it becomes true
, the operation should clean up its resources and terminate.
A CancellationToken
can also be used to register callbacks that will be executed when cancellation is requested. This is done by calling the Register
method on the token.
CancellationToken()
Initializes a new instance of the CancellationToken
struct.
None
Gets a token that will never be cancelled.
CanBeCanceled
Gets a value that indicates whether this token can be canceled. If the token was created from a CancellationTokenSource
, this property returns true
; otherwise, it returns false
.
IsCancellationRequested
Gets a value that indicates whether cancellation has been requested for this token.
CancellationLinkedToken
Gets the token that represents the combined cancellation state of all linked tokens. If no tokens are linked, this property returns the current token.
Equals(object obj)
Determines whether the specified object is equal to the current instance.
Equals(CancellationToken other)
Determines whether the specified CancellationToken
is equal to the current instance.
GetHashCode()
Returns the hash code for this instance.
Register(Action callback)
Registers a delegate to be called when cancellation is requested. Returns a CancellationTokenRegistration
that can be used to unregister the callback.
Parameters:
callback
: The delegate to be called when cancellation is requested.
Returns:
A CancellationTokenRegistration
that can be used to unregister the callback.
Register(Action<object> callback, object state)
Registers a delegate to be called when cancellation is requested, along with a state object. Returns a CancellationTokenRegistration
that can be used to unregister the callback.
Parameters:
callback
: The delegate to be called when cancellation is requested.state
: The state object to pass to the callback.
Returns:
A CancellationTokenRegistration
that can be used to unregister the callback.
Register(Action<object> callback, object state, CancellationToken cancellationToken)
Registers a delegate to be called when cancellation is requested, along with a state object and a specific cancellation token. Returns a CancellationTokenRegistration
that can be used to unregister the callback.
Parameters:
callback
: The delegate to be called when cancellation is requested.state
: The state object to pass to the callback.cancellationToken
: The cancellation token to observe.
Returns:
A CancellationTokenRegistration
that can be used to unregister the callback.
ThrowIfCancellationRequested()
Throws a OperationCanceledException
if cancellation has been requested for this token.
operator ==(CancellationToken left, CancellationToken right)
Compares two CancellationToken
instances for equality.
operator !=(CancellationToken left, CancellationToken right)
Compares two CancellationToken
instances for inequality.
The following example demonstrates how to use CancellationToken
to cancel an asynchronous operation.
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 long-running operation...");
var operationTask = PerformLongRunningOperation(token);
// Simulate cancelling the operation after 2 seconds
await Task.Delay(2000);
Console.WriteLine("Cancelling operation...");
cts.Cancel();
try
{
await operationTask;
Console.WriteLine("Operation completed successfully.");
}
catch (OperationCanceledException)
{
Console.WriteLine("Operation was cancelled.");
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
}
public static async Task PerformLongRunningOperation(CancellationToken cancellationToken)
{
for (int i = 0; i < 10; i++)
{
// Check if cancellation has been requested
cancellationToken.ThrowIfCancellationRequested();
Console.WriteLine($"Operation step {i + 1}...");
await Task.Delay(500); // Simulate work
}
Console.WriteLine("Operation finished its work.");
}
}