Monday, March 4, 2013

Adding async/await support to WP7 projects

When porting changes made to a Windows Phone 8 app back to the Windows Phone 7.x version I ran into an issue due to the lack of async/await support.

Turns out you can add the Microsoft.Bcl.Async Nuget package to add support for Async in Windows Phone 7.x. Note that at this time it is prerelease, so you may need to indicate as such to nuget to install it.

Once added I could then create some extension methods for the Live SDK to convert the event pattern to the async pattern:

    public static class LiveConnectClientExtension
    {
        public static Task GetAsyncTask(this LiveConnectClient client, string path)
        {
            var tcs = new TaskCompletionSource();
            client.GetCompleted += (s,e) => 
            {
                if (e.Error != null) tcs.TrySetException(e.Error);
                else if (e.Cancelled) tcs.TrySetCanceled();
                else tcs.TrySetResult( new LiveOperationResult(e.Result, e.RawResult));
            };
            client.GetAsync(path);
            return tcs.Task;
        }
    }

Critical Sections

Now that things are occurring asynchronously their is the possibility of the user triggering multiple threads. See Awaitable critical section for a tidy solution.

See Also: