Windows Phone Choosers with async/await

Currently, Windows Phone Choosers work is by invoking the Show method and then subscribing the Completed event and waiting for it to be invoked.

Wouldn’t it be great to just use await chooser.ShowAsync() and get the results immediately?

All choosers extend the [ChooserBase](http://msdn.microsoft.com/en-us/library/windowsphone/develop/ff707923(v=vs.105).aspx) class, and it's exactly for this class that we are going to use to create a ShowAsync extension method.

We start by creating the extension method signature:

public static class ExtensionMethods
{
    public static Task<TTaskEventArgs> ShowAsync<TTaskEventArgs>(this ChooserBase<TTaskEventArgs> chooser)
        where TTaskEventArgs : TaskEventArgs
    {
    }
}

The async methods are required to return void, Task, or Task in order to be invoked with the await keyword. So our method will return a Task value, where the TTaskEventArgs generic type must be a [TaskEventArgs](http://msdn.microsoft.com/en-US/library/windowsphone/develop/microsoft.phone.tasks.taskeventargs(v=vs.105).aspx) subtype.

We will need to use a TaskCompletionSource object so we can return a Task and later on set the result of the asynchronous operation.

var taskCompletionSource = new TaskCompletionSource<TTaskEventArgs>();

Next we will add the code for the normal Chooser handling:

EventHandler<TTaskEventArgs> completed = null;

completed = (s, e) => {
    chooser.Completed -= completed;

    taskCompletionSource.SetResult(e);
};

chooser.Completed += completed;
chooser.Show();

Notice that we are removing the event handler after it gets invoked as not to have a memory leak! All that is missing now is just returning the Task object:

return taskCompletionSource.Task;

And that’s it!

Here’s how the full extension method should look:

public static class ExtensionMethods {
    public static Task<TTaskEventArgs> ShowAsync<TTaskEventArgs>(this ChooserBase<TTaskEventArgs> chooser)
        where TTaskEventArgs : TaskEventArgs
    {
        var taskCompletionSource = new TaskCompletionSource<TTaskEventArgs>();

        EventHandler<TTaskEventArgs> completed = null;

        completed = (s, e) => {
            chooser.Completed -= completed;

            taskCompletionSource.SetResult(e);
        };

        chooser.Completed += completed;
        chooser.Show();

        return taskCompletionSource.Task;
    }
}

You can download a sample code for this directly from the Microsoft Code Gallery.

The PhoneApplicationFrame bug is still alive!

This is an issue that I stomped about 6 months ago, blogged about it, reported and got it confirmed by Microsoft, and just found out that after all this time, they didn’t fix it on Windows Phone 8!!

When the Windows Phone SDK started to allow developers to remove entries from the navigation back stack, they (inadvertly?) introduced a bug in PhoneApplicationFrame, more specifically in the CanGoBack property!

Here’s how to simulate the issue:

  • Start by creating two separate pages
  • On the application start page, add a Button that when clicked will just navigate to the second page (thus adding an item to the navigation stack)
  • On the second page Loaded event, call the NavigationService.RemoveBackEntry (removing the previously added item from the navigation stack)
  • Get the current PhoneApplicationFrame instance with (PhoneApplicationFrame)App.Current.RootVisual
  • Compare the NavigationService.CanGoBack and PhoneApplicationFrame.CanGoBack property values: the first indicates false, the correct and expected value, while the second indicates true, something that should not happen because we just cleared the navigation back stack when we removed the only entry that was there!!

By using a Reflection tool to look at the PhoneApplicationFrame implementation, one could easily realize that while the methods Navigate, GoBack, RemoveBackEntry and others are just proxies to the same ones on NavigationService, this is not true for the CanGoBack and CanGoForward properties, which have local values and only get updated after a navigation event!

And this is where lies the whole problem: the values ​​of these properties should be obtained directly from NavigationService like the methods are, or at least they should also be updated when RemoveBackEntry method gets called!

You can test and confirm this bug by downloading this sample application.

All you need to do is run the app, click on “Navigate to self”, check that the stack count is now 1, click on one of the two buttons for the “RemoveBackEntry” and realize that the CanGoBack properties now have different values!

This situation has been fixed in the implementation of the INavigationService on Cimbalino Windows Phone Toolkit, but be aware that there are still a lot of similar services implementations from other toolkits and frameworks that have this bug…

Updated on 20/01/2013: After a few tweets with Joost van Schaik, he updated the INavigationService implementation on Wp7nl utilities to match the Cimbalino Windows Phone Toolkit.

Welcome!

My name is Pedro Lamas, I’m a Portuguese developer specialized in Microsoft Technologies, and this is my English blog for Windows and Windows Phone Development.

For a while this address was home for my Portuguese blog Nação do Cimbalino. Rest assure that the blog still exists, it just got moved to a new address!

I’ll be working to get the blog up and running in the next few days, so please bare with me.

I promise it will be worth it! ;)