Tag Archives: Asynchronous

Understanding Cancellation Callbacks

, , , ,

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 CancellationToken and CancellationTokenSource, the answers to these questions revolve around when cancellation occurs and how it is triggered.
Continue reading

async/await Doesn’t Make Synchronous Code Asynchronous

, ,

With the recent release of .Net 4.5/C# 5, I’ve spent time experimenting with the new async/await functionality. To my surprise, these new keywords didn’t have the effect I anticipated. Based on my skimming of pre-release information, I was under the impression that the appropriate use of these keywords would cause a normally-synchronous method to execute asynchronously.

Wrong! Continue reading