Cancellation Tokens

Object that can be passed around, and is used to signal if a service has been requested to stop. This allows you to stop cleanly.

Note a cancellation token will not stop the entire program it, is just a token, managed by its source.

Types

using var cancellationTokenSource = new CancellationTokenSource();

CancellationToken token = cancellationTokenSource.Token; // use this token

cancellationTokenSource.Cancel();

CancellationTokenSource

CancellationToken

Patterns

Typically you get a token and pass it down the call stack, and then act on it.

Stop while loop when requested

while (!cancellationToken.IsCancellationRequested)
{
    DoWork();
}

Throw exception when requested

cancellationToken.ThrowIfCancellationRequested();

Timeouts

using var cancellationTokenSource = new CancellationTokenSource(
    TimeSpan.FromSeconds(30));

await DoWork(cancellationTokenSource.Token);

Linking tokens

You can make it so if the caller token cancels or the timeout happens, the new linked token will cancel

using var timeoutCts = new CancellationTokenSource(
    TimeSpan.FromSeconds(30));

using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(
    callerToken,
    timeoutCts.Token);

await DoWork(linkedCts.Token);

How you should use it

You can either pass a cancellationToken or pass CancellationToken.None.

cancellationToken

CancellationToken.None