16
Oct
12

Coroutines are dead. Long live Coroutines.

As many of you may have already heard, Caliburn.Micro was recently ported to WinRT thanks to Nigel Sampson and Keith Patton.

Either if you are doing Windows 8 development or working with WPF and .NET Framework 4.5, you are probably eagerly playing working with the powerful asynchronous programming support in Visual Studio 2012. (Not yet? Go study it NOW).

For those using Caliburn and Caliburn.Micro, a very neat kind of asynchronous programming has been available since 2009: have a look at this Rob’s blog post introducing IResult and Coroutines, one year before Async CTP!

But now async/await stuff is going to be mainstream; does it mean that IResult and Coroutines are becoming useless?
My initial opinion is that they could be kept just for backward compatibility, but they turned out to be still quite important for some reasons.

Access to execution context

In several scenarios the action defined in the ViewModel requires to gain direct access to the view or to the element triggering the action itself.
The view instance could be obtained using GetView method on Screen class (or implementing IViewAware), but the triggering element instance is not that easy to reach.

Moreover, while in some cases using an “Model-View-Presenter-like” approach is the only viable solution, generally speaking ViewModels should not control the UI directly, nor deal with presentation concerns at all.

Custom IResult, instead, provides an easy access to a class called ActionExecutionContext, which contains all the objects involved into the action execution: the containing view, the triggering element, the ViewModel instance, the method called, etc.
So, while creating ad-hoc IResults for simple asynchronous service calls could be tedious, using custom, reusable IResult to isolate UI concerns is quite effective, and helps to clean out ViewModels code.

Testability

It’s entirely possible testing async code written using async/await, usually replacing real services with mocks. Yet, using an IEnumerable<IResult> in the ViewModel allows to just test the returned “sequence”, without actually executing each IResult.

Action execution “wrapping”

Caliburn.Micro can map (using conventions or an explicit DSL) an event occurring on the UI side to a method call on the ViewModel side.
As a consequence, it’s very easy to turn a simple void method into an asynchronous one (async void or async Task), and let Caliburn.Micro to start its execution.

I don’t recommend this approach, however: this way, indeed, the action execution (from CM’s point of view) completes as soon as a Task object is created, while the actual async method execution usually take longer. Also, exceptions thrown during execution may go unobserved (see http://blogs.msdn.com/b/pfxteam/archive/2011/09/28/10217876.aspx) because the Task object is not available anymore.

For these reasons I wrote a simple extension taking care of it; the strategy I chose is to customize CM’s action invocation code, in order to intercept async methods returning Tasks and wrap them into an IResult.
This way I could simply take advantage of the existing infrastructure; in particular, I can use the builtin notification of Coroutines completion (Coroutine.Complete static event), which also bring information about possible exception occurred.

Here the relevant code:

public static class AsyncAwaitSupport
{
	public static void Hook()
	{

		ActionMessage.InvokeAction = context =>
		{

			var values = MessageBinder.DetermineParameters(context, context.Method.GetParameters());
			var returnValue = context.Method.Invoke(context.Target, values);

			var task = returnValue as Task;
			if (task != null)
			{
				returnValue = new TaskResult(task);
			}

			var result = returnValue as IResult;
			if (result != null)
			{
				returnValue = new[] { result };
			}

			var enumerable = returnValue as IEnumerable;
			if (enumerable != null)
			{
				Coroutine.BeginExecute(enumerable.GetEnumerator(), context);
				return;
			}

			var enumerator = returnValue as IEnumerator;
			if (enumerator != null)
			{
				Coroutine.BeginExecute(enumerator, context);
				return;
			}
		};
	}

	private class TaskResult : IResult
	{
		Task task;
		public TaskResult(Task task)
		{
			if (task == null) throw new ArgumentNullException("task");
			this.task = task;
		}

		public event EventHandler Completed = delegate { };

		public void Execute(ActionExecutionContext context)
		{
			task.ContinueWith(t =>
			{
				Completed(this, new ResultCompletionEventArgs {
                                            WasCancelled = t.IsCanceled,
                                            Error = t.Exception }
                                       );
			});
		}
	}

}

The extension is hooked during the bootstrapper initialization:

protected override void Configure()
{
    base.Configure();

    AsyncAwaitSupport.Hook();

    //...
}

Once I have this in place, I could translate the following code (taken from CoroutineViewModel.cs inside Caliburn.Micro.WinRT.Sample):

public IEnumerable ExecuteCoroutine()
{
	yield return new VisualStateResult("Loading");
	yield return new DelayResult(2000);
	yield return new VisualStateResult("LoadingComplete");
	yield return new MessageDialogResult("This was executed from a custom IResult, MessageDialogResult.", "IResult Coroutines");
}

into something like this:

public async Task ExecuteTask()
{
	this.SetVisualStateOnView("Loading");

	await Task.Delay(2000);

	this.SetVisualStateOnView("LoadingComplete");

	//This is just a sample: I don't actually recommend calling UI code from here in real code.
	var dialog = new Windows.UI.Popups.MessageDialog("This was executed with a regular MessageDialog.", "Async/await");
	await dialog.ShowAsync();
}

[Here the same post in Italian language]

About these ads


October 2012
S M T W T F S
« May    
 123456
78910111213
14151617181920
21222324252627
28293031  

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: