1 minute read

Asynchronous code is different from parallel programming. Asynchronous code uses continuation while parallel code uses thread. What is continuation? It’s easier to understand if you write the async code manually. There are a few types of manual async pattern.

EAP, Event-based Asynchronous Pattern

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;
}

IAsyncResult Callback

private void LookupHostName()
{
    object unrelatedObject = "hello";
    Dns.BeginGetHostAddresses("oreilly.com", OnHostNameResolved, unrelatedObject);
}

private void OnHostNameResolved(IAsyncResult ar)
{
    object unrelatedObject = ar.AsyncState;
    IPAddress[] addresses = Dns.EndGetHostAddresses(ar);

    // Do something with addresses
    ...
}

Callback

void GetHostAddress(string hostName, Action<IPAddress> callback)

private void LookupHostName()
{
    GetHostAddress("oreilly.com", OnHostNameResolved);
}

private void OnHostNameResolved(IPAddress address)
{
    // Do something with address
    ...
}

private void LookupHostName()
{
    int aUsefulVariable = 3;
    GetHostAddress("oreilly.com", address =>
        {
            // Do something with address and aUsefulVariable
            ...
        });
}

But all these approaches has lots of disadvantages, not to mention the infamous callback hell.

The Task Parallel Library was introduced in version 4.0 of the .NET Framework. Its most important class is Task, which represents an ongoing operation. A generic version, Task, acts as a promise of a value (of type T) that will be available in the future, once the operation is done.

Tags: ,

Updated:

Comments