Chapter 3. Writing Asynchronous Code Manually

In this chapter, we’ll talk about writing asynchronous code without the help of C# 5.0 and async. In a way, this is going over techniques you’ll never have to use, but it’s important to help understand what’s really happening behind the scenes. Because of this, I’ll go over the examples quickly, only drawing out the points that are helpful in understanding.

Some Asynchronous Patterns Used in .NET

As I mentioned before, Silverlight only provides asynchronous versions of APIs like web access. Here is an example of how you might download a web page and display it:

private void DumpWebPage(Uri uri)
{
    WebClient webClient = new WebClient();
    webClient.DownloadStringCompleted += OnDownloadStringCompleted;
    webClient.DownloadStringAsync(uri);
}

private void OnDownloadStringCompleted(object sender,
    DownloadStringCompletedEventArgs eventArgs)
{
    m_TextBlock.Text = eventArgs.Result;
}

This kind of API is called the Event-based Asynchronous Pattern (EAP). The idea is that instead of a single synchronous method to download the page, which blocks until it’s done, one method and one event are used. The method looks just like the synchronous version, except it has a void return type. The event has a specially defined EventArgs type, which contains the value retrieved.

We sign up to the event immediately before calling the method. The method returns immediately, of course, because this is asynchronous code. Then, at some point in the future, the event will fire, ...

Get Async in C# 5.0 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.