CancellationToken Struct

System.Threading

Summary

Represents an operation that can be cancelled. This type is used to propagate cancellation signals across asynchronous operations.

Syntax
public struct CancellationToken
Remarks

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.

Constructors
constructor CancellationToken()
public CancellationToken()

Initializes a new instance of the CancellationToken struct.

Fields
field None
public static readonly CancellationToken None

Gets a token that will never be cancelled.

Properties
property CanBeCanceled
public bool CanBeCanceled { get; }

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.

property IsCancellationRequested
public bool IsCancellationRequested { get; }

Gets a value that indicates whether cancellation has been requested for this token.

property CancellationLinkedToken
public CancellationToken CancellationLinkedToken { get; }

Gets the token that represents the combined cancellation state of all linked tokens. If no tokens are linked, this property returns the current token.

Methods
method Equals(object obj)
public override bool Equals(object obj)

Determines whether the specified object is equal to the current instance.

method Equals(CancellationToken other)
public bool Equals(CancellationToken other)

Determines whether the specified CancellationToken is equal to the current instance.

method GetHashCode()
public override int GetHashCode()

Returns the hash code for this instance.

method Register(Action callback)
public CancellationTokenRegistration 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.

method Register(Action<object> callback, object state)
public CancellationTokenRegistration 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.

method Register(Action<object> callback, object state, CancellationToken cancellationToken)
public CancellationTokenRegistration 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.

method ThrowIfCancellationRequested()
public void ThrowIfCancellationRequested()

Throws a OperationCanceledException if cancellation has been requested for this token.

method operator ==(CancellationToken left, CancellationToken right)
public static bool operator ==(CancellationToken left, CancellationToken right)

Compares two CancellationToken instances for equality.

method operator !=(CancellationToken left, CancellationToken right)
public static bool operator !=(CancellationToken left, CancellationToken right)

Compares two CancellationToken instances for inequality.

Example

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.");
    }
}