Async Samples Part 1

I’ve decided to follow the process I used when I learned LINQ to the new async features coming in the next version of C#. Longtime blog readers will remember that I took each of the 101 LINQ samples, and posted my notes while running and examining them. 

Lucian Wischik has published the samples (using Silverlight) here. This is the source for what I’m writing about.

Today, I’ll cover the introductory sample. All the new language keywords are demonstrated here. The first sample shows a simple web request:

public async void AsyncIntroSingle()
{
WriteLinePageTitle(
await new WebClient()
.DownloadStringTaskAsync(new Uri(http://www.weather.gov)));
}

This code says: create a new WebClient, and tell it to download the weather channel site asynchronously. After starting the async download, yield control to the caller of this method. When that task (the download) has finished, continue by passing its result to WriteLinePageTitle.

Let’s contrast that with the C# 4.0 version (also from Lucian’s site):

public void AsyncIntroSingleBefore()
{
var client = new WebClient();

client.DownloadStringCompleted +=
AsyncIntroSingleBefore_DownloadStringCompleted;
client.DownloadStringAsync(new Uri("http://www.weather.gov"));
}

void AsyncIntroSingleBefore_DownloadStringCompleted(object sender,
DownloadStringCompletedEventArgs e)
{
WriteLinePageTitle(e.Result);
}

I hope that the first version is simpler (despite its unfamiliarity). This older version exposes more of the internal processes to make this happen.

It still creates a WebClient. But, before starting the download, this code wires up the event handler for the continuation method. Then, it starts the download. Notice that the code running after the download completes is now in another method.

Things to Remember:

Methods that have the async modifier are asynchronous methods. That means their evaluation is discontinuous. There evaluation may be suspended when an await expression is encountered.

await suspends execution of an asynchronous function until the task completes. Await may only appear in an asynchronous method (among other restrictions.) When code awaits something, the current method exits, only to have control switch back to it when the awaited operation completes.

The big concept:  These new language features enable us to write code that looks like it is executing synchronously, but actually does execute asynchronously. The code reads as a sequential program: do this, then do that, then do something else. However, it executes asynchronously: do this, (while waiting for this to continue, go keep busy), then do that, then do the other thing. The justification is that we write programs that utilize more cores, or communicate with more devices on the network. We want to write and read those programs sequentially, because they are easier to understand. These new features will make that easier.

Comments are closed.