In the ideal world, all .Net asynchronous methods support cancellation tokens: When invoking a method, simply pass it a cancellation token. Then, at the appropriate time, cancel the token and the asynchronous operation terminates.
Alas! We don’t live in the ideal world. Not every method we might asynchronously invoke works with cancellation tokens. When faced with an asynchronous operation we want to be able to cancel that doesn’t support cancellation tokens, one option is to implement our own cancellation logic by registering a callback with the token. When the token is cancelled, callbacks registered with it are executed.
Introducing callback into the picture raises questions around if/when, where and how those callbacks are executed. For example:
- Will the callback be invoked via the synchronization context that was current when it was registered?
- If multiple callbacks are registered, are they run synchronously or in parallel?
- If a callback raises an exception, can that exception be caught?
In the case of .Net’s Task Parallel Library and its
CancellationTokenSource, the answers to these questions revolve around when cancellation occurs and how it is triggered.