When you are dealing with an application that directly interacts with a network, or works on network resources, your app is bound to make some long running calls. If we were dealing with a good old Windows Forms application, the most important point was to avoid your application from blocking the UI. We would use some background threads or a background worker, while displaying a (relatively annoying) loading sign. We could extend this pattern by using some completed or error event handlers to notify the UI about the worker thread. The basic goal here is to let the user know that the application is doing some work in the background without blocking the UI thread, hence avoiding the “MyApp is not responding” status.

In Windows Store Apps, our job is a little harder. We have to deal with the whole “Fast and Fluid” ideology of windows runtime. In other words, our application should stay responsive at all times. We can still use some subtle indicators that the application is doing something in the background but we should avoid keeping the user waiting while we are finishing up a task. In this quest of ours to make our application responsive, our biggest helper is the new asynchronous API. With this new “framework”, you can implement/use progress callbacks, task abortion, awaiter’s and so on; by means of which you can throw some of the basic plumbing on windows runtime’s back.

In this post, we will be implementing and using some of the features of this asynchronous API. For this purpose lets create a new class that works on a simple eventing pattern. We will have a long running task, a Completed handler and an error event.

So our operation just waits for 2000 milliseconds and if the input value is less than 0 throws an exception. Otherwise, it will return a result value. (NOTE: Task.Delay is very similar to Thread.Sleep function from the Threading namespace).

As we described above we need two events for success and error. So we first implement the event arguments:

The reason we are using the Task.Run function is the fact that this is the easiest way to execute our function on a separate ThreadPool on windows runtime. We are just emulating the background operation with an async thread.

So now our usage for this class and its functions would be something like:

Great, we have an asynchronous pattern implemented using events. We can now move forward using some of the asynchronous API features.

Converting Events to Awaitables (TaskCompletionSource<T>)

One of the most useful features from the async framework is the TaskCompletionSource. Using the task awaiter developers can easily convert legacy async event implementations to awaitables. So in our example, we can actually write an additional method in our wrapper class to convert the execution for Task 1 to an awaitable.

As you notice from the comments, you have two main actions with the task completion source. On a successful call we set the result, on a failed call, we set the error / exception. And to actually call our method now, we can use all the features in an async awaitable call:

Voilà! We converted the event based async implementation to an awaitable method.

Converting Event Pattern to Async Pattern (Task<T>>)

In the previous example, we refrained from changing the EventingClass. This class was maybe a legacy implementation, or there was quite a big amount of business logic implemented and it would be troublesome to implement awaitables.

However, what if you have access to EventingClass and the energy to rewrite the public access methods. In this case, let us get rid of all event related implementations and just deal with our async implementation.

Our long running DoTask1 method is now executed as an awaitable. And just like in the previous example, you can call it with a simple try catch block.

Chaining / Batching Tasks (ContinueWith / WhenAll / WhenAny)

Let us now assume, we have three tasks (i.e. Task1, Task2, Task3), all receiving an input parameter of integer type and returning integer. Moreover, let’s assume we have to write a function that executes all of these methods in an awaitable fashion.

For this scenario, we set the following synchronous methods to be executed.

If we were using the old eventing implementation we would have to chain the callbacks in the Completed events for each of these methods and handle the error. However with the ContinueWith<T> callback implementation we can easily chain these methods and have an awaitable parent function:

In addition to ContinueWith, you are also equipped with functions like WhenAll and WhenAny. These functions are pretty self-explanatory. And the usage pattern would look something similar to the function declaration below if these tasks we have were mutually exclusive.

Can Bilgin works in CompuSight Corp as a Senior Software Architect. He has been working in software industry with Microsoft technologies for over a. In this period he took key roles in projects for high profile clients such as Microsoft, General Electric, Raiffeisen Bank, Jettainer and Adobe Echosign using technologies such as BizTalk, SharePoint, InfoPath, Windows Mobile, Windows Phone, WinRT and WCF.He is especially interested in Windows 8 (WinRT) platform and windows phone development. He tries to share his experience on his blog and through different MSDN activities. He regularly attends local Microsoft conferences and community events in the Balkan region.He is a Microsoft MVP with Windows Platform Development expertise.His team recently received the Best Productivity App Award from Windows Store Application Contest by Qualcom.