Sobes.tech
Junior — Middle

Kas saaksite selgitada tühistamise märgi kontseptsiooni mitme lõime programmeerimise kontekstis?

sobes.tech AI

Vastus AI-lt

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

Main idea: one thread (or component) can request the cancellation of an operation, and others executing that operation can periodically check the token's state and terminate correctly if cancellation is requested.

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

  • CancellationTokenSource creates a token and can signal cancellation.
  • CancellationToken is passed to tasks or methods that can check IsCancellationRequested and react 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, request cancellation
cts.Cancel();

This allows safely and controllably interrupting long-running or background operations.