Cover by Alex Davies

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

O'Reilly logo

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, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required