Running an async operation from a synchronous function

One of those things that you almost never need, but if you need it, you need it. I hit a scenario where in Windows Phone 8 app, I had to have a Protocol launch handler. If you are not familiar, the protocol launch handler in Windows Phone 8 is done by deriving from the UriMapper class (Irrelevant but interesting fact: in Windows 8.0, 8.1 and WP 8.1, you handle protocol activation from an OnActivated event handler). What I did not count on was that I will be making an async call from the MapUri function which handles the protocol activation of the app.

Usually, the way I handle an async call within a function is to mark the containing function async as well.. i.e. just following the chain till everything is marked async. Unfortunately, the signature of the MapUri function is fixed. It looks like:

1
public override Uri MapUri(Uri uri)

As you can see, trying to muck with the signature and make it ‘async’ does not go well with the compiler which complains.

Anyways, a bit of research revealed that you can await an async call in the following way without having to add the ‘async’ keyword to the containing function:

1
2
3
  var task = Task.Run(async () => await MyAsyncFunction()
  task.Wait();
  var asyncFunctionResult = task.Result;

So, I can finally write my async function within the synchronous MapUri in the following manner:

1
2
3
4
5
6
public override Uri MapUri(Uri uri)
{
  var task = Task.Run(async () => await MyAsyncFunction()
  task.Wait();
  var asyncFunctionResult = task.Result;
}

Hope this helps.

Leave a comment

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