Async CTP (SP1 Refresh)

By Jeremy Meng

Visual Studio Async CTP (SP1 Refresh) is available now! You are welcome to download and try it out!

Thanks to the new Async feature coming in Visual Basic and C# it has never been so easy to write asynchronous code. With the newly introduced async and await keywords you can make asynchronous calls without having to create callback functions, sign them up to some ****Completed events, retrieve results from EventArgs by yourself. Visual Basic and C# compiler will do the plumbing work for you.

I hope that the following example can help you get basic ideas on how the Async feature makes writing responsive applications easier.

Here is a simple WPF application to get you started with Async in C#. This WPF app has a label, a button, and a checkbox on its UI. When the button is clicked, the application will perform a query over the network (for example, downloading files from the internet, querying data from a database, etc.) After the query is done, the label will be updated to show the length of the returned string data.

The event handler for button click:

private void button1_Click(object sender, RoutedEventArgs e)

{

    UpdateLabel();

}

async void UpdateLabel()

{

    NetworkClass nc = new NetworkClass();

    int i = 0;

    i = await nc.MethodQueryingNetworkAsync();

    label1.Content = "Length: " + i;

}

 

The code for MethodQueryingNetworkAsync() is like below:

async public Task<int> MethodQueryingNetworkAsync()

{

    // Querying a slow website with network latency so that

    // the result comes back after a certain amount of time

    WebClient wc = new WebClient();

    string content = await wc.DownloadStringTaskAsync(
        new Uri("https://some.slow.website/"));

    return content.Length;

}

 

Run the application and click on the button, you will still be able to toggle the checkbox on UI while the network query is executing. When the downloading is finished, the label will be updated to show the length of the query result. During the query execution, the UI is completely responsive.

What’s new in Visual Studio Async CTP SP1 Refresh?

  • It is compatible with Visual Studio 2010 SP1 and Windows Phone 7. The previous Async CTP only works for Visual Studio 2010 RTM.
  • More efficient Async methods!

We changed the old pattern of GetAwaiter/BeginAwait/EndAwait with the new pattern of GetAwaiter/IsCompleted/OnCompleted/GetResult. This provides better performance especially if the task we are awaiting had already completed. We also make exception behaviors uniform in void-returning async methods (Async Subs in Visual Basic).

  • Many bug fixes since the release of the previous Async CTP. Thanks for the feedbacks from the community! Please let us know what you think!

For more details, read on Lucian’s blog. Welcome to Async and happy asynchronous coding!