Home > Articles > Programming > Windows Programming

  • Print
  • + Share This
Like this article? We recommend Asynchronous Support

Asynchronous Support

The entire Metro platform was built with performance in mind. Any tasks that could potentially take longer than 50ms are defined asynchronously. Asynchronous programming has been around since the earliest days of Windows development, but it hasn’t always been easy. Silverlight enforced asynchronous communications, and this created some angst as developers struggled to handle these operations while keeping their code base clean, maintainable, and easy to understand. To illustrate the point, consider a set of asynchronous APIs that must be called in sequence for breakfast, lunch, and dinner. To ensure that the breakfast API completes before the lunch API is fired and so forth, your code would have to look something like this:

private void EatMeals() 
     MealProxy.BreakfastCompleted +=
         (o, e) =>

                 BreakfastResult = e.Result;
                 MealProxy.LunchCompleted +=
                     (o1, e1) =>
                             LunchResult = e.Result;
                             MealProxy.DinnerCompleted +=
                                 (o2, e2) =>
                                         DinnerResult = e.Result;
                         };                 MealProxy.EatLunchAsync(null);

For this example, I demonstrated the methods using lambda expressions. You could also register methods for the event handler delegates, but that would result in multiple methods and the need to pass state between calls. You’ll have to go that route if you intend to call the methods multiple times to keep from re-registering the same event handlers. Fortunately, Metro is based on Visual Studio 11 and the .NET Framework 4.5. These new tools include support for new language keywords that make it easy to handle asynchronous processes. The async keyword flags a method as containing asynchronous components, while the await keyword triggers an asynchronous process and resumes execution when it completes without blocking the main thread.

The same code shown above looks like this in an async world:

private async void EatMeals() 
     BreakfastResult = await MealProxy.EatBreakfastAsync();
     LunchResult = await MealProxy.EatLunchAsync();
     DinnerResult = await MealProxy.EatDinnerAsync(); 

While developers may need some time to get used to the new keywords, they definitely make asynchronous development easier.

  • + Share This
  • 🔖 Save To Your Account