Sobes.tech
Junior — Middle

Can you explain the concept of a cancellation token in the context of multithreaded programming?

sobes.tech AI

Answer from AI

Cancellation Token in multithreaded programming is an object used to coordinate the cancellation of asynchronous or parallel operations.

The main idea: one thread (or component) can request cancellation, and others performing the operation can periodically check the token's state and terminate correctly if cancellation is requested.

In C#, this is implemented through the CancellationToken and CancellationTokenSource classes:

  • CancellationTokenSource creates a token and can signal cancellation.
  • CancellationToken is passed to tasks or methods, which can check IsCancellationRequested and respond to cancellation.

Example:

var cts = new CancellationTokenSource();
var token = cts.Token;

Task.Run(() => {
    while (!token.IsCancellationRequested)
    {
        // Perform work
    }
    // Cleanup and finish
}, token);

// Somewhere in the code, call cancel
cts.Cancel();

This allows safely and controllably interrupt long or background operations.