Async Lambda Expression
By | August 26, 2011

Do you know what is coming next to C#? Asynchronous programming is really made easy with the inclusion of new contextual keywords to C# namely async and await. If you are unaware of it, I would really suggest you to read few of my posts like :

C# 5.0 vNext
Async support for Silverlight and WP7
Debugging with Async

There are lots more. Today I will discuss how you can benefit your application using Async delegates with async lambda expressions.

Lamda expressions are not new to .NET. It has been introduced as a part of linq representing a short form of a delegate in .NET 3.5. With the introduction of it, we (the developers) are totally inclined to use this short form of a method and write Inversion of Control for our application. The popularity of Lambda expression demands the support of async anonymous methods just like the normal async methods.

Lets know more about it from a sample code :

private async void Button_Click(object sender, RoutedEventArgs e)
{
    Func<Task> asyncLambda = async () =>
        {
            MessageBox.Show("Async Call");
            await TaskEx.Delay(10000);
            MessageBox.Show("Async Call End");
        };

    await RunMe(asyncLambda);
}


public Task RunMe(Func<Task> runner)
{

    if (runner != null)
        return TaskEx.RunEx(runner);

    return null;
}

Here in the code RunMe is a normal method that accepts Func<Task> delegate. Once it receives, it invert the control at sometime to call the method during the actual execution of the method.

Button_Click is an EventHandler which is marked as async (hence supports asynchronous invocation). I have declared an annonymous method of async and called RunMe with the same. Now as RunMe returns an object of Task, you can easily await on the same.

Thus when you run this application, the application will show you the first MessageBox and after 10 seconds (because we use TaskEx.Delay) the second MessageBox will appear, but the thing that you should notice, that it would make the application responsive even though it is waiting and also you do not need to use Dispatcher to invoke MessageBoxes.

This is the importance of Async.

Important Note:
Notice I have used TaskEx rather than original Task class. Actually in this CTP release, Task isn’t capable of running the async lambda, and hence you do not have any option rather than use TaskEx. But after this is actually released, you would find it in actual Task object.

Download Sample Application

I hope you like this post.

Thanks ! icon smile Async Lambda Expression