Tag Archives: async

Async programming model

Convert Events to Async methods

If you are familiar with .net 4.5 (or 4.0 with Microsoft.Bcl) you might have met with the async await pattern. After implementing a few classes I started to like it and prefer it over event, inline methods, delegates and so on… I am going to explain why in another post but this time I just want to show a way to refactor old libraries to async pattern.

In the below example I wrap the LiveConnectClient 5.3 API’s GetAsync method which doesn’t support async methods yet. I used delegates to properly remove the event avoiding memory leaks faulty behaviour.

public class LiveConnectClientTaskAsync
    {
        private LiveConnectSession session;
        private LiveConnectClient client;

        public LiveConnectClientTaskAsync(LiveConnectSession session)
        {
            this.session = session;
            client = new LiveConnectClient(session);
        }

        public async Task<LiveOperationCompletedEventArgs> GetTaskAsync(string command)
        {
            var tcs = new TaskCompletionSource<LiveOperationCompletedEventArgs>();

            EventHandler<LiveOperationCompletedEventArgs> handler = delegate(object o, LiveOperationCompletedEventArgs e)
            {
                if (e.Error != null)
                {
                    tcs.TrySetException(e.Error);
                }
                else if (e.Cancelled)
                {
                    tcs.TrySetCanceled();
                }
                else
                {
                    tcs.TrySetResult(e);
                }
            };

            client.GetCompleted += handler;
            client.GetAsync(command);

            LiveOperationCompletedEventArgs eventArgs = await tcs.Task;

            client.GetCompleted -= handler;

            return eventArgs;
        }

After the code is compiled you can use the GetTaskAsync method with await and your executing thread will be released till the operation is done. 🙂

LiveOperationCompletedEventArgs e = await client.GetTaskAsync("me/skydrive/files");
Advertisements