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
- You use this object to request that the service should be stopped
CancellationToken
- You use this object to check if the service should stop
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
- Means you are ok for this method to stop, we are in a safe space
- For example
- Reading data is probs fine
- Anything that is idempotent, and has retry
CancellationToken.None
- Means the called method not be cancelled, we are not in a safe space
- For example
- We might be doing multiple writes that all must complete (you should be using a transaction in this case)
- Anything that is not idempotent
- Small critical areas
- Where partial completion might leave things in an ambiguous state