Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

CancellationTokenSource — requesting cancellation and releasing resources

CancellationTokenSource manages cooperative cancellation through a CancellationToken. Cancel requests that work stop, whereas Dispose releases resources and does not cancel operations.

Version: .NET 10; repository net10.0 and LangVersion=preview; feature versions require per-entry verification

Syntax

using var source = new CancellationTokenSource();
CancellationToken token = source.Token;
source.Cancel();
// source.Dispose() is called automatically at the end of the scope.

System.Threading.CancellationTokenSource exposes through Token a token passed to operations. Cancel() sets IsCancellationRequested to true in every copy of that token. Cancellation is cooperative: receiving code must respond; the request itself does not forcibly terminate a thread. CancelAfter(...) schedules a request after a specified delay.

CancellationTokenSource.Dispose() releases resources but does not request cancellation and does not replace waiting for work to finish. The source's owner should dispose of it when finished, for example through using. Do not use the source afterward. Call Dispose() only after all other operations on that source have completed; it must not run concurrently with them.

The net10.0 example reads the token state, calls Cancel(), and reads the state again. Leaving the using block calls Dispose() before the final message. Having no timers or background tasks makes the output order deterministic.

Examples

using System;
using System.Threading;

using (var source = new CancellationTokenSource())
{
    CancellationToken token = source.Token;
    Console.WriteLine($"Before: {token.IsCancellationRequested}");

    source.Cancel();

    Console.WriteLine($"After: {token.IsCancellationRequested}");
}

Console.WriteLine("Source disposed.");

Result

Before: False
After: True
Source disposed.

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources