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?
The callback registered with
CancellationToken.Registeris executed on the thread that callsCancellationTokenSource.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:
and the output is:
Hope this helps.