Take a look at the documentation for CancellationToken.Register
:
If this token is already in the canceled state, the delegate will be run immediately and synchronously. Any exception the delegate generates will be propagated out of this method call.
The current ExecutionContext, if one exists, will be captured along with the delegate and will be used when executing it.
Consider the following:
void RegisterBeforeCancel(CancellationToken token)
{
token.Register(() => Console.WriteLine("Before cancel"));
}
void RegisterAfterCancel(CancellationToken token)
{
token.Register(() => Console.WriteLine("After cancel"));
}
var cts = new CancellationTokenSource();
RegisterBeforeCancel(cts.Token);
cts.Cancel();
RegisterAfterCancel(cts.Token);
The output will show:
Before cancel
After cancel