Monday, July 26, 2010

Implementing Asynchronous Callbacks with Task Parallel Library

Bored again...so thought of posting how you can implement callback with Task Parallel Library (TPL).

So what am I talking here, basically I start a task in one thread and I want it to call another method once it completes (Asynchronous callbacks ).

Here is a sample code....

Task<int> parent = new Task<int>(
() =>
{
Console.WriteLine("In parent");
return 100; }
);


Task<int> child = parent.ContinueWith( a =>
{
Console.WriteLine("In Child");
return 19 + a.Result;
});

parent.Start()

Console.WriteLine(child.Result);

The code explains it all, all I have to do is create the task and then call its ContinueWith method and register the callback, its important to note that the parent task is an input to the continuation callback and the result of the parent can be accessed by the callback.

The callback is again another Task, so it does not block the calling thread.
The callback in TPL gives you more flexibility, in the way you want the callback to be invoked, for an example I can specify that I want the callback to be invoked only if the parent did not run successfully to the end.

I can re-write the above code to do that exactly by passing in a TaskContinuationOptions option as the 2nd parameter of the ContinueWith method.

Task<int> parent = new Task<int>(
() =>
{
Console.WriteLine("In parent");
return 100; }
);


Task<int> child = parent.ContinueWith( a =>
{
Console.WriteLine("In Child");
return 19 + a.Result;
},
TaskContinuationOptions.NotOnRanToCompletion
);

parent.Start()

Console.WriteLine(child.Result);

The option is bitwise so I can specify several options demarcated by the pipe line. A few important options would be NotOnCanceled, OnlyOnRanToCompletion, OnlyOnFaulted etc

No comments:

Post a Comment