Question

In the absence of constructing a quick test bed; I thought I would quickly ask SO to see if anyone knows that answer off hand.

Plus it might have the added benefit of informing other users who may encounter similar situations..

Let's say I have a long lived CancellationTokenSource with many many different components registering handlers on the CancellationToken.

If cancel is requested and the registered callbacks are all invoked and then following that point another handler is registered; does the cancel callback still fire for that new call back at the point of registration?

Cheers in advance!

Was it helpful?

Solution

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top