Async callback to awaitable Task<>

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.

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/white-space: pre;/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

  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.

1 thought on “Async callback to awaitable Task<>”

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from Tedds blog

Subscribe now to keep reading and get access to the full archive.

Continue reading