Thursday, April 12, 2012

Task based Asynchronous pattern, Async & Await and .NET 4.5

One of the key features in .Net 4.5 is to write asynchronous programs much easier. So if I was to write asynchronous programs in .Net 2.0/3.5, I would either follow the event based model or the callback based model. For an example, a synchronous method that does intensive work (say the DoWork()) can be made asynchronous by using the following patterns

1) Implementing the IAsyncResult pattern. in this implementation, 2 methods are exposed for the DoWork() synchronous method, the BeginDoWork() and the EndDoWork() method. The user will call the BeingDoWork() passing in the required parameters and a callback of the delegate type AsyncCallback(IAsyncResult). The BeginDoWork() will spawn a new thread a return control back to the user. Once work is completed in the spawned method, as a last step, it will call the inform the AsyncResult implementation, which in turns will call the EndDoWork() (which is the callback that was passed in to the BeginDoWork()).

2) Implementing the event pattern. Here a BeginDoWork() is implemented but an event is exposed, so that the user can subscribe to that event. The event is invoked by the implementation once the method completes.

.Net 4.0 introduced Tasks, the Task object exposes a continuation feature by which it becomes much more easier to write asynchronous programs. Using this feature, i can assign some work to the task to be executed in a separate thread and then subscribe a continuation to executed once the primary task is done.
       Task<int> task = new Task<int>(() =>
{/*Do intensive work here*/ return 100; });
task.ContinueWith(t => { Console.WriteLine("Result is -- " + t.Result); });
task.Start();
In .Net 4.5 this becomes much easier with the async and await keywords. So the same program can be written like this...
     private async static void InvokeAsync()
{
int val = await WorkAsync();
//This is your continuation code...
Console.WriteLine("Result is -- " + val);
}
The async keyword tells the compiler that this method is an asynchronous method. Once the compiler sees the await method, it subscribes the rest of the code i.e the consoling (in this case) and any other logic as a continuation to the Task object returned by the WorkAsync(), control is given to the main thread.
The WorkAsync method creates a Task object that encapsulate the work that needs to be done and returns it. The await keyword works on the Task object returned by the WorkAsync()

The WorkAsync() method would be like this...
     private static Task<int> WorkAsync()
{
//Do intensive work here...
Task<int> task = new Task<int>(() =>
{/*Do stuff here*/ return 1000; });
task.Start();
return task;
}
Essentially, the await keyword is used at the point where your are doing some work in a separate thread, this is usually through a Task class, the rest of the method after the await call is the callback method. It is interesting to note that you can use multiple await calls inside a async meth
Practically, you would not need to implement the WorkAsync() method, as most of the asynchronous version of APIs also support a XXXAsync() in .net 4.5, that can be directly used with the await keyword. For an example, WCF proxy's would now expose Task based asynchronous method so it can work with the await keyword.

2 comments:

  1. Any idea on how this works with the asp.net page lifecycle? does the continuation code get executed before PreRenderComplete like all other async tasks?

    ReplyDelete
  2. Nandun, PageAsyncTask is a way to execute asynchronous code an return the processing thread to the asp.net worker pool. You can do almost do the same thing with Tasks, you can create a task that calls the web service and subscribe a continuation method for the callback. You can start the task and then run it on the ThreadPool...this would be similar to what you do with PageAsyncTasks...now in in you Page pre render you can do a Task.WaitAll() to wait untill all the threads complete......

    The other approach is to use the PageAsyncTask and plug in the Task into it. PageAsyncTask works on the IasyncResult pattern, Task implement the same pattern, so you can integrate this easily. Let me know if you need more information

    ReplyDelete