Asynchronous lambda expressions

March 20, 2011

Not only methods but also lambda expressions can be async. Among other things this allows event handlers to be anonymous:

sumButton.Click += async (sender, e) => {
    sumButton.IsEnabled = false;
    await SumPageSizesAsync(GetUrls());
    sumButton.IsEnabled = true;
AddHandler sumButton.Click, Async Function(sender, e)
                                sumButton.IsEnabled = False
                                Await SumPageSizesAsync(GetUrls())
                                sumButton.IsEnabled = True
                            End Function

Another useful application of asynchronous lambdas is for running asynchronous work on a background thread. Task.Run has overloads that expect delegates of type Func<Task> and Func<Task<TResult>> so that you can easily express this.

One Response to “Asynchronous lambda expressions”

  1. When I am eager to see more Posts from you on latest technologies. I bookmarked your site.

Leave a Reply

You must be logged in to post a comment.