Asynchronous Lambdas and Local Functions

Just as a lambda expression converted to a delegate can be used as a concise syntax for declaring a normal method, lambdas containing await expressions can be converted to delegates.14 To do so, just precede the lambda expression with the async keyword. In Listing 20.10, we first assign an async lambda to a Func<string, Task> writeWebRequestSizeAsync variable. We then use the await operator to invoke it.

Listing 20.10: An Asynchronous Client-Server Interaction as a Lambda Expression
1. using System;
2. using System.IO;
3. using System.Net;
4. using System.Linq;
5. using System.Threading.Tasks;
6.  
7. public class Program
8. {
9.  
10.     public static void Main(string[] args)
11.     {
12.         string url = "http://www.IntelliTect.com";
13.         if(args.Length > 0)
14.         {
15.             url = args[0];
16.         }
17.  
18.         Console.Write(url);
19.  
20.         Func<string, Task> writeWebRequestSizeAsync =
21.             async (string webRequestUrl) =>
22.             {
23.                 // Error handling omitted for 
24.                 // elucidation
25.                 WebRequest webRequest =
26.                    WebRequest.Create(url);
27.  
28.                 WebResponse response =
29.                     await webRequest.GetResponseAsync();
30.  
31.                 // Explicitly counting rather than invoking
32.                 // webRequest.ContentLength to demonstrate
33.                 //  multiple await operators
34.                 using (StreamReader reader =
35.                     new(response.GetResponseStream()))
36.                 {
37.                     string text =
38.                         (await reader.ReadToEndAsync());
39.                     Console.WriteLine(
40.                         FormatBytes(text.Length));
41.                 }
42.             };
43.  
44.         Task task = writeWebRequestSizeAsync(url);
45.  
46.         while (!task.Wait(100))
47.         {
48.             Console.Write(".");
49.         }
50.     }
51.     // ...
52. }

Similarly, the same effect can be achieved with a local function.15 For example, in Listing 20.10, you could change the lambda expression header (everything up to and including the => operator) to

async Task WriteWebRequestSizeAsync(string webRequestUrl)

leaving everything in the body, including the curly braces, unchanged.

Note that an async lambda expression has the same restrictions as the named async method:

An async lambda expression must be converted to a delegate whose return type is a valid async return type.
The lambda is rewritten so that return statements become signals that the task returned by the lambda has completed with the given result.
Execution within the lambda expression occurs synchronously until the first await on an incomplete awaitable is executed.
All instructions following the await will execute as continuations on the return from the invoked asynchronous method (or, if the awaitable is already complete, simply will be executed synchronously rather than as continuations).
An async lambda expression can be invoked with an await operator (not shown in Listing 20.10).
AdVanced/Beginner Topic
Implementing a Custom Asynchronous Method

Implementing an asynchronous method by relying on other asynchronous methods (which, in turn, rely on more asynchronous methods) is relatively easy with the await keyword. However, at some point in the call hierarchy, it becomes necessary to write a “leaf” asynchronous Task-returning method. Consider, for example, an asynchronous method for running a command-line program with the eventual goal that the output could be accessed. Such a method would be declared as follows:

public static Task<Process> RunProcessAsync(string filename)

The simplest implementation would, of course, be to rely on Task.Run() again and call both the System.Diagnostics.Process’s Start() and WaitForExit() methods. However, creating an additional thread in the current process is unnecessary when the invoked process itself will have its own collection of one or more threads. To implement the RunProcessAsync() method and return to the caller’s synchronization context when the invoked process completes, we can rely on a TaskCompletionSource<T> object, as shown in Listing 20.11.

Listing 20.11: Implementing a Custom Asynchronous Method
1. using System.Diagnostics;
2. using System.Threading;
3. using System.Threading.Tasks;
4.  
5. public class Program
6. {
7.     public static Task<Process> RunProcessAsync(
8.         string fileName,
9.         string arguments = "",
10.         CancellationToken cancellationToken = default)
11.     {
12.         TaskCompletionSource<Process> taskCS =
13.                       new();
14.  
15.         Process process = new()
16.         {
17.             StartInfo = new ProcessStartInfo(fileName)
18.             {
19.                 UseShellExecute = false,
20.                 Arguments = arguments
21.             },
22.             EnableRaisingEvents = true
23.         };
24.  
25.         process.Exited += (sender, localEventArgs) =>
26.         {
27.             taskCS.SetResult(process);
28.         };
29.  
30.         cancellationToken
31.             .ThrowIfCancellationRequested();
32.  
33.         process.Start();
34.  
35.         cancellationToken.Register(() =>
36.         {
37.             Process.GetProcessById(process.Id).Kill();
38.         });
39.  
40.         return taskCS.Task;
41.     }
42.     // ...
43. }

Ignore the highlighting for the moment and instead focus on the pattern of using an event for notification when the process completes. Since System.Diagnostics.Process includes a notification upon exit, we register for this notification and use it as a callback from which we can invoke TaskCompletionSource.SetResult(). The code in Listing 20.11 follows a fairly common pattern that you can use to create an asynchronous method without having to resort to Task.Run().

Another important characteristic that an async method might require is cancellation. TAP relies on the same methods for cancellation as the TPL does—namely, a System.Threading.CancellationToken. Listing 20.11 highlights the code necessary to support cancellation. In this example, we allow for canceling before the process ever starts, as well as an attempt to close the application’s main window (if there is one). A more aggressive approach would be to call Process.Kill(), but this method could potentially cause problems for the program that is executing.

Notice that we don’t register for the cancellation event until after the process is started. This avoids any race conditions that might occur if cancellation is triggered before the process actually begins.

One last feature to consider supporting is a progress update. Listing 20.12 is the full version of RunProcessAsync() with just such an update.

Listing 20.12: Implementing a Custom Asynchronous Method with Progress Support
1. using System;
2. using System.Diagnostics;
3. using System.Threading;
4. using System.Threading.Tasks;
5.  
6. public class Program
7. {
8.     public static Task<Process> RunProcessAsync(
9.         string fileName,
10.         string arguments = "",
11.         IProgress<ProcessProgressEventArgs>? progress = 
12.             nullobject? objectState = null,
13.         CancellationToken cancellationToken =
14.             default(CancellationToken))
15.     {
16.         TaskCompletionSource<Process> taskCS = new();
17.  
18.         Process process = new()
19.         {
20.             StartInfo = new ProcessStartInfo(fileName)
21.             {
22.                 UseShellExecute = false,
23.                 Arguments = arguments,
24.                 RedirectStandardOutput =
25.                    progress is not null
26.             },
27.             EnableRaisingEvents = true
28.         };
29.  
30.         process.Exited += (sender, localEventArgs) =>
31.         {
32.             taskCS.SetResult(process);
33.         };
34.  
35.         if (progress is not null)
36.         {
37.             process.OutputDataReceived +=
38.                 (sender, localEventArgs) =>
39.             {
40.                 progress.Report(
41.                     new ProcessProgressEventArgs(
42.                         localEventArgs.Data,
43.                         objectState));
44.             };
45.         }
46.  
47.         cancellationToken
48.             .ThrowIfCancellationRequested();
49.  
50.         process.Start();
51.  
52.         if (progress !=null)
53.         {
54.             process.BeginOutputReadLine();
55.         }
56.  
57.         cancellationToken.Register(() =>
58.         {
59.             Process.GetProcessById(process.Id).Kill();
60.         });
61.  
62.         return taskCS.Task;
63.     }
64.  
65.     // ...
66. }
67.  
68. public class ProcessProgressEventArgs
69. {
70.     // ...
71. }

Wrapping your head around precisely what is happening in an async method can be difficult, but it is far less difficult than trying to figure out what asynchronous code written with explicit continuations in lambdas is doing. The key points to remember are as follows:

When control reaches an await keyword, the expression that follows it produces a task.16 Control then returns to the caller so that it can continue to do work while the task completes asynchronously (assuming it hadn’t already completed).
Sometime after the task completes, control resumes at the point following the await. If the awaited task produces a result, that result is then obtained. If it faulted, the exception is thrown.
A return statement in an async method causes the task associated with the method invocation to become completed; if the return statement has a value, the value returned becomes the result of the task.

________________________________________

14. Starting in C# 5.0.
15. Starting in C# 7.0.
16. Technically, it is an awaitable type, as described in the “Advanced Topic: Valid Async Return Types Expanded.”
{{ snackbarMessage }}
;