Using Caliburn.Micro with async/await

Jul 15, 2013

This post will give an overview of how you can use async/await features from C# 5.0 with Caliburn.Micro (CM). If you’ve found an error or want to complete the content please let me know in the comments. A sample application demonstrating async/await interactions in CM is available on GitHub.

Setting it up

To use Tasks and async/await features you need the latest version of Caliburn.Micro. Support for Tasks was introduced in version 1.5, so you’ll need a version higher than that. And, of course, you need .NET Framework 4.5 or higher. All examples in this post were tested in a WPF application targeting .NET 4.5 framework. However, same code will be probably valid for Silverlight, WP8 and Windows8 apps.

Create and configure new project to test the concepts

Create new WPF 4.5 application

Install Caliburn.Micro from nuget. You’d better choose the Caliburn.Micro.Start package as it has everything required to run a Caliburn application (boostrapper, container, main screen)

Convert coroutines to Tasks

“async void” or “async Task”

A great question will be: should I use async void or async Task as a return value of action methods, screen’s events and overrides? Since you can do both and the code will compile and run mostly fine, let’s see what Stephen Cleary writes about it in Best Practices in Asynchronous Programming article:

You should prefer async Task to async void. Async Task methods enable easier error-handling, composability and testability. The exception to this guideline is asynchronous event handlers, which must return void. This exception includes methods that are logically event handlers even if they’re not literally event handlers (for example, ICommand.Execute implementations).

I will join this recommendation. Actions are event handlers at their core, normally they are executed as “start and forget”. If something happens (an exception), it will be handled at application level. For the case when you want to handle any exceptions locally, you may want to create an override which returns an async Task. Also, this will allow calling same method action from another part of the program or write a unit test to verify an asynchronous process.