On which thread is a CancellationToken's registered callback invoked when it is requested from another thread?

42 views Asked by At

Suppose I have a task running in another thread, with a cancellation callback (from Register) registered during that thread's execution.

Then the owner of the CancellationTokenSource invokes Cancel from the main thread. Where/when is the cancellation callback invoked? In the main thread where the cancellation was requested, or in the background thread where it was registered?

1

There are 1 answers

0
Rafal Kozlowski On

The callback registered with CancellationToken.Register is executed on the thread that calls CancellationTokenSource.Cancel(). So, if you invoke Cancel from the main thread, the callback will be executed on the main thread. It will not be executed on the background thread where the callback was registered.

An example:

var cts = new CancellationTokenSource();
var token = cts.Token;

Task.Run(() =>
{
    token.Register(() =>
    {
        Console.WriteLine($"Callback executed on thread {Thread.CurrentThread.ManagedThreadId}");
    });
    
    Console.WriteLine($"Background thread {Thread.CurrentThread.ManagedThreadId}");
    // Simulate some work
    Thread.Sleep(2000);
});

Console.WriteLine($"Main thread {Thread.CurrentThread.ManagedThreadId}");
Thread.Sleep(500); // Give the background task some time to start and register the callback
cts.Cancel();

and the output is:

Main thread 1
Background thread 20
Callback executed on thread 1

Hope this helps.