Cancellation Token in C#

The CancellationToken in C# is a versatile tool for managing asynchronous operations and providing a means to cancel them gracefully. Let's dive deeper into its usage, additional features, and best practices.

Key Components

CancellationTokenSource: This is used to create tokens and signal cancellation to the associated tokens.

CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();

CancellationToken: Represents the token that can be checked for cancellation. It is retrieved from the CancellationTokenSource.

CancellationToken cancellationToken = cancellationTokenSource.Token;

Passing CancellationToken to Operations

Task-based Methods: Most asynchronous methods in .NET that support cancellation accept a CancellationToken As an optional parameter. For instance.

async Task SomeAsyncOperation(CancellationToken cancellationToken)
{
    await Task.Delay(1000, cancellationToken); // Example with Task.Delay supporting cancellation
    // Other asynchronous operations
}

Cancellation Request: To signal cancellation to a token, use the Cancel() method of the associated CancellationTokenSource.

cancellationTokenSource.Cancel();

Handling Cancellation

Checking for Cancellation: Inside the asynchronous method, use IsCancellationRequested property to check if cancellation is requested.

while (!cancellationToken.IsCancellationRequested)
{
    // Perform work here
}

Catching OperationCanceledException: Wrap the code that may throw an OperationCanceledException due to cancellation within a try-catch block.

try
{
    // Code that may throw OperationCanceledException
}
catch (OperationCanceledException)
{
    // Handle cancellation here
}

Best Practices

  1. Early Cancellation Checks: Check the cancellation token frequently, especially before long-running operations, to ensure timely cancellation.
  2. Exception Handling: Catch OperationCanceledException to perform cleanup or any necessary actions upon cancellation.
  3. Passing Tokens: Ensure proper passing of cancellation tokens through your asynchronous methods and down the call chain if required.
  4. Cancellation Chaining: Use CancellationTokenSource methods like CreateLinkedTokenSource() to create tokens that are linked and can be canceled together.

Example

async Task LongRunningOperation(CancellationToken cancellationToken)
{
    try
    {
        while (!cancellationToken.IsCancellationRequested)
        {
            // Check for cancellation before any significant operation
            cancellationToken.ThrowIfCancellationRequested();

            // Perform work here
            await Task.Delay(1000); // Simulate a delay
        }
    }
    catch (OperationCanceledException)
    {
        // Cleanup or handle cancellation
    }
}

Conclusion

The CancellationToken and CancellationTokenSource classes are crucial for implementing cancellation in asynchronous operations, ensuring responsive and well-behaved code. By using these features effectively, you can create robust and cancellable asynchronous workflows in C#.


Similar Articles