Event-Based Asynchronous Pattern in .NET 4.5 and C# 2012

Professional C# 2012 and .NET 4.5The method OnAsyncEventPattern makes use of the event-based asynchronous pattern. This pattern is implemented by the WebClient class and thus it can be directly used.

This pattern defines a method with the suffix "Async". Therefore, for example, for the synchronous method DownloadString, the WebClient class offers the asynchronous variant DownloadStringAsync. Instead of defining a delegate that is invoked when the asynchronous method is completed, an event is defined. The DownloadStringCompleted event is invoked as soon as the asynchronous method DownloadStringAsync is completed. The method assigned to the event handler is implemented within a Lambda expression. The implementation is very similar to before, but now it is possible to directly access UI elements because the event handler is invoked from the thread that has the synchronization context, and this is the UI thread in the case of Windows Forms and WPF applications (Chapter 13 code file AsyncPatterns/MainWindow.xaml.cs):

    private async void OnTaskBasedAsyncPattern(object sender, 
        RoutedEventArgs e)
      foreach (var req in GetSearchRequests())
        var client = new WebClient();
        client.Credentials = req.Credentials;
        string resp = await client.DownloadStringTaskAsync(req.Url);
        IEnumerable<SearchItemResult> images = req.Parse(resp);
        foreach (var image in images)

An advantage of the event-based asynchronous pattern is that it is easy to use. Note, however, that it is not that easy to implement this pattern in a custom class. One way to use an existing implementation of this pattern to make synchronous methods asynchronous is with the BackgroundWorker class. BackgroundWorker implements the event-based asynchronous pattern.

This makes the code a lot simpler. However, the order is reversed compared to synchronous method calls. Before invoking the asynchronous method, you need to define what happens when the method call is completed. 

This article is excerpted from Wrox’s Professional C# 2012 and .NET 4.5 (Copyright 2013 John Wiley & Sons, ISBN: 978-1-1183-1442-5) by Christian Nagel, Bill Evjen, Jay Glynn, Karli Watson, Morgan Skinner.



Leave a Reply

Your email address will not be published. Required fields are marked *