Async callback to awaitable Task<>

By | 2013.09.13

The Async-Await feature in .Net is really super. At least until it comes to debugging, exception handling and race conditions. In short it cuts down on code, bugs, complexity and allows for linear programming. Traditional async programming uses callbacks (events) that adds to code complexity, it also forces an unnatural break in your code.

Luckily more and more .Net-objects is getting support for async-await, and the most important ones are already implemented.

However, there is also a very easy way to convert a traditional async into async-await. In the sample code below I have made an awaitable task out of the camera for WP7, but this can be applied to any async callback.

  1. Create a TaskCompletionSource with return type.
  2. Set up your traditional async, but in the callback (done) event pass result on to TaskCompletionSource.
  3. Return TaskCompletionSource.Task to waiting method.

To use this code simply:

This will not block GUI-thread, but return result on it. No need to use Dispatcher, dedicated background thread or async callback.

One thought on “Async callback to awaitable Task<>

Leave a Reply