C# 6.0 in a Nutshell by Joseph Albahari & Ben Albahari

C# 6.0 in a Nutshell by Joseph Albahari & Ben Albahari

Author:Joseph Albahari & Ben Albahari
Language: eng
Format: epub, pdf
Publisher: O'Reilly Media, Inc.
Published: 2015-11-15T16:00:00+00:00


The compiler’s ability to manufacture tasks for asynchronous functions means that for the most part, you need to explicitly instantiate a TaskCompletionSource only in bottom-level methods that initiate I/O-bound concurrency. (And for methods that initiate compute-bound currency, you create the task with Task.Run.)

Asynchronous call graph execution

To see exactly how this executes, it’s helpful to rearrange our code as follows:

async Task Go() { var task = PrintAnswerToLife(); await task; Console.WriteLine ("Done"); } async Task PrintAnswerToLife() { var task = GetAnswerToLife(); int answer = await task; Console.WriteLine (answer); } async Task<int> GetAnswerToLife() { var task = Task.Delay (5000); await task; int answer = 21 * 2; return answer; }

Go calls PrintAnswerToLife, which calls GetAnswerToLife, which calls Delay and then awaits. The await causes execution to return to PrintAnswerToLife, which itself awaits, returning to Go, which also awaits and returns to the caller. All of this happens synchronously, on the thread that called Go; this is the brief synchronous phase of execution.

Five seconds later, the continuation on Delay fires and execution returns to GetAnswerToLife on a pooled thread. (If we started on a UI thread, execution now bounces to that thread). The remaining statements in GetAnswerToLife then run, after which the method’s Task<int> completes with a result of 42 and executes the continuation in PrintAnswerToLife, which executes the remaining statements in that method. The process continues until Go’s task is signaled as complete.

Execution flow matches the synchronous call graph that we showed earlier because we’re following a pattern whereby we await every asynchronous method right after calling it. This creates a sequential flow with no parallelism or overlapping execution within the call graph. Each await expression creates a “gap” in execution, after which the program resumes where it left off.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.