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:
CancellationTokenSourcecreates a token and can signal cancellation.CancellationTokenis passed to tasks or methods that can checkIsCancellationRequestedand 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.