Sony Arouje

a programmer's log

Archive for November 30th, 2010

Using await in asynchronous programming

with one comment

In the recent release of VS Async CTP introduced a new way of placing async calls using await. I did a small analysis with the Async CTP. Based on my limited analysis I felt like the new CTP wont make much difference in making WCF calls from silverlight, only workarounds. In other hand the new feature is good to develop asynchronous API’s much clean and easier.

First lets see how we normally make async calls, for the demo I choose webclient as it is easy.

WebClient wc = new WebClient();
wc.DownloadStringCompleted += (o, e) =>
    if (e.Error == null)
        //do our work

wc.DownloadStringAsync(new Uri(“, null);


In the above approach the call will be done in single method. Then what’s the use of await, leme explain. Think about a scenario were, you wanted to call the twitter api and the function should return the result. The current scenario it’s not possible. The function will return back to the caller before the async calls completed. Here is were the await will come into picture.

I am going to rewrite the code using await. To use new CTP, I need to refer AsyncCtpLibrary.dll located in C:\Users\<UserName>\Documents\Microsoft Visual Studio Async CTP\Samples. Add namespace  system.threading.tasks

private static async Task<string> DownloadGoogleHomePageAsync()
    WebClient wc = new WebClient();
    var byteArr = await wc.DownloadDataTaskAsync(new Uri(""));
    return System.Text.Encoding.ASCII.GetString(byteArr);

as you can see above my new function will return the result of the async call. This approach eradicate the anonymous or lambda way of calling the async function. With this approach we can do an if condition check or what ever we need just like a normal function call.

I can call the above function as shown below.

string content = DownloadGoogleHomePageAsync().Result;

I am not going to explain the more technical details here. MSDN has a white paper giving an in depth knowledge of await and Task based programming.

Await In Silverlight

Await functionality is also available in Silverlight. I will be more happy if I could able to call a WCF service using await from Silverlight. Currently WCF wont serialize Task/Task<T>, so there is no direct way of calling await with a WCF service method. One workaround is mentioned in the msdn forum, I haven’t tried yet. I use Reactive extension to call async methods.

In one of Amadeo Casas blog mentioned that WCF team is working to adopt async model. I am awaiting for the WCF vNext release :).

Await in Real Life scenario

See my other post to see how to use await in real life scenario like doing a time consuming database call or doing a time consuming algorithm.

Written by Sony Arouje

November 30, 2010 at 7:20 pm

Posted in .NET, Silverlight

Tagged with ,

%d bloggers like this: