Sobes.tech
Junior — Middle

What are the consequences of canceling an operation using CancellationToken?

sobes.tech AI

Answer from AI

If an operation is canceled using a CancellationToken, then:

  • The launched task should respond correctly to the cancellation request by checking the token's state and interrupting execution.
  • If the task does not check the token, cancellation will not occur immediately — the operation will continue.
  • Typically, an OperationCanceledException is thrown upon cancellation, which can be handled for proper termination.
  • Cancellation allows freeing resources and avoiding unnecessary work, improving application responsiveness.

Example of cancellation check:

async Task DoWorkAsync(CancellationToken token) {
    for (int i = 0; i < 100; i++) {
        token.ThrowIfCancellationRequested();
        // Perform part of the work
        await Task.Delay(100);
    }
}

If the token is canceled, the method will throw an exception, and execution will be interrupted.