Sobes.tech
Middle

What is CancellationToken in multithreading?

sobes.tech AI

Answer from AI

CancellationToken is used to request cancellation of an asynchronous or long-running operation in multithreading, allowing flexible control over task execution and preventing thread blocking.

It consists of:

  • CancellationTokenSource: The token source that creates a CancellationToken and allows requesting cancellation (Cancel()).
  • CancellationToken: The token itself, which is passed to the cancellable operation. It contains the property IsCancellationRequested, indicating whether cancellation has been requested. The cancellable operation can also use the method ThrowIfCancellationRequested() to immediately throw an OperationCanceledException.

Example usage:

// Create a token source
var cts = new CancellationTokenSource();
var token = cts.Token;

// Start a task, passing the token
var task = Task.Run(() =>
{
    for (int i = 0; i < 1000; i++)
    {
        // Check if cancellation has been requested
        if (token.IsCancellationRequested)
        {
            Console.WriteLine("Cancellation requested.");
            // Optionally throw an exception
            // token.ThrowIfCancellationRequested();
            break;
        }
        Console.WriteLine($"Iteration {i} in progress");
        Thread.Sleep(100); // Simulate work
    }
}, token);

// Wait some time and request cancellation
Thread.Sleep(500);
cts.Cancel();

// Wait for the task to complete
task.Wait();

Advantages of using CancellationToken:

  • Control: Allows external code to request cancellation of an ongoing operation.
  • Flexibility: The cancellable operation itself determines how to respond to the cancellation request (immediately terminate, perform cleanup before finishing, etc.).
  • Code cleanliness: Provides a structured cancellation mechanism instead of manual flag management or other synchronization methods.
  • Integration: Well integrates with task-based asynchronous operations (Task, async/await) and other .NET libraries supporting cancellation.