Asynchronous Programming with Async and Await (links)

Found another good article covering this topic.

http://tech.pro/tutorial/1180/asynchronous-programming-in-c-using-async-and-await

This link covers many approaches for asynchronous programming.

http://www.codeproject.com/Articles/562021/Asynchronous-models-and-patterns

Advertisements

Asynchronous Programming with Async and Await

Check out this article on MSDN for a new feature in VS 2012 which makes asynchronous programming easier.  Here’s a brief summary:

Summary

Visual Studio 2012 RC introduces an approach that relies on two keywords, the Async (Visual Basic) or async (C#) modifier and the Await (Visual Basic) or await (C#) operator. The async modifier indicates to the compiler that a method or lambda expression is asynchronous and that suspension points can be designated within it by using an await operator. Such a method is referred to as an async method.

Inside an async method, you apply an await operator to a particular task to suspend execution of the async method until the task is complete. In the meantime, control is returned to the caller of the async method while the task completes its work. The suspension is accomplished without actually exiting from the async method, and finally blocks don’t run.

The compiler does the difficult work that the developer used to do, including signing up continuations for the completion of the suspended method. As a result, asynchronous code is much easier to write, and your program retains a logical structure that is similar to synchronous code. In addition, routine processes that can be difficult in traditional asynchronous code, such as loops and exception handling, cease to be roadblocks to successful solutions. For more information about previous approaches to asynchrony in the .NET Framework, see TPL and Traditional .NET Asynchronous Programming.

The .NET 4.5 Framework contains many members that work with async and await. You can recognize these members by the “Async” suffix that’s attached to the member name and a return type of Task or Task<TResult>. For example, the System.IO.Stream class contains methods such as CopyToAsyncReadAsync, and WriteAsync alongside the synchronous methods CopyToRead, and Write.

Example

The following code example shows a method written twice. The first is a synchronous version and the second is an asynchronous version using the new keywords “async” and “await”.

// Synchronous version of a method that downloads the resource that a URL
// links to and returns its content.
private byte[] GetURLContents(string url)
{
    // The downloaded resource ends up in the variable named content.
    var content = new MemoryStream();

    // Initialize an HttpWebRequest for the current URL.
    var webReq = (HttpWebRequest)WebRequest.Create(url);

    // Send the request to the Internet resource and wait for
    // the response.
    using (var response = webReq.GetResponse())
    {
        // Get the data stream that is associated with the specified URL.
        using (Stream responseStream = response.GetResponseStream())
        {
            // Read the bytes in responseStream and copy them to content.
            responseStream.CopyTo(content);
        }
    }

    // Return the result as a byte array.
    return content.ToArray();
}

// Asynchronous version of the same method. The changed lines

are marked with **.

// **Change the method name and the return type. Add the async modifier.
private async Task<byte[]> GetURLContentsAsync(string url)
{
    // The downloaded resource ends up in the variable named content.
    var content = new MemoryStream();

    // Initialize an HttpWebRequest for the current URL.
    var webReq = (HttpWebRequest)WebRequest.Create(url);

    // **Call GetResponseAsync instead of GetResponse, and await the result.
    // GetResponseAsync returns a Task.
    using (WebResponse response = await webReq.GetResponseAsync())
    {
        // Get the data stream that is associated with the specified URL.
        using (Stream responseStream = response.GetResponseStream())
        {
            // ** Call CopyToAsync instead of CopyTo, and await the response.
            // CopyToAsync returns a Task, not a Task.
            await responseStream.CopyToAsync(content);
        }
    }
    // Return the result as a byte array.
    return content.ToArray();
}

Click here to view a video of another example.