- Overview of Asynchrony
- The Old-Fashioned Way: Event-Based Asynchrony
- The Old-Fashioned Way: The Asynchronous Programming Model
- The Modern Way: The Async Pattern
- Getting Started with Async/ Await
- Exception Handling in Async
- Implementing Task-Based Asynchrony
- Cancellation and Progress
- Asynchronous Lambda Expressions
- Asynchronous I/O File Operations in .NET 4.6
- Debugging Tasks
- Summary
Asynchronous Lambda Expressions
Methods can be asynchronous, but so can lambda expressions. To be asynchronous, a lambda must have the Async modifier and must return Task or Task(Of T), but it cannot accept ByRef arguments and cannot be an iterator function. A lambda can be asynchronous when its code uses the Await operator to wait for a Task result. An example of asynchronous lambdas is with event handlers. For instance, you might need to wait for the result of a task when an event is raised, as in the following code snippet that handles a button’s Click:
AddHandler Me.Button1.Click, Async Sub(sender, e) Await DoSomeWorkAsync End Sub
You do not need an asynchronous lambda if the work you are going to execute does not return a Task. Another typical usage of asynchronous lambdas is with Task.Run. The following code shows the same example described when introducing Task.Run, but now the lambda that starts the intensive work is marked with Async and the method that actually performs intensive computations returns a Task so that it can be awaited:
Private Async Sub RunIntensiveWorkAsync() cancellationToken = New CancellationTokenSource 'This runs on the UI thread Console.WriteLine("Starting...") Try 'This runs on a Thread Pool thread Dim result As Integer = Await Task.Run(Async Function() Dim workResult As Integer = _ Await _ SimulateIntensiveWorkAsync() Return workResult End Function) 'This runs again on the UI thread Console.WriteLine("Finished") Catch ex As OperationCanceledException Console.WriteLine("Canceled by the user.") Catch ex As Exception End Try Console.ReadLine() End Sub Private Async Function SimulateIntensiveWorkAsync() As Task(Of Integer) Dim delay As Integer = 1000 Await Task.Delay(delay) Return delay End Function
This code simulates CPU-intensive work inside an asynchronous method. However, this is not best practice and should be avoided when possible. Here it is shown for demonstration purposes only. For additional tips about asynchronous methods, visit http://channel9.msdn.com/Series/Three-Essential-Tips-for-Async/Async-Library-Methods-Shouldn-t-Lie.