async
and await
Before async
and await
, it was common for a method that was called synchronously (i.e., performing tasks one after another in order) in the calling thread to launch a long-running task asynchronously and to provide that task with a callback method (or, in some cases, register an event handler) that would be invoked once the asynchronous task completed. This style of coding is simplified with async
and await
.
async
ModifierThe async
modifier indicates that a method or lambda expression contains at least one await
expression. An async
method executes its body in the same thread as the calling method. (Throughout the remainder of this discussion, we’ll use the term “method” to mean “method or lambda expression.”)
await
ExpressionAn await
expression, which can appear only in an async
method, consists of the await
operator followed by an expression that returns an awaitable entity—typically a Task
object (as you’ll see in Section 23.3), though it is possible to create your own awaitable entities. Creating awaitable entities is beyond the scope of our discussion. For more information, see
http://blogs.msdn.com/b/pfxteam/archive/2011/01/13/10115642.aspx
When an async
method encounters an await
expression:
If the asynchronous task has already completed, the async
method simply continues executing.
Otherwise, program control returns to the async
method’s caller until the asynchronous task completes execution. This allows the caller to perform other work that does not depend on the results of the asynchronous task.
When the asynchronous task completes, control returns to the async
method and continues with the next statement after the await
expression.
The mechanisms for determining whether to return control to an async
method’s caller or continue executing an async
method, and for continuing an async
method’s execution when the asynchronous task completes, are handled entirely by code that’s written for you by the compiler.
async, await
and ThreadsThe async
and await
mechanism does not create new threads. If any threads are required, the method that you call to start an asynchronous task on which you await
the results is responsible for creating the threads that are used to perform the asynchronous task. For example, we’ll show how to use class Task
’s Run
method in several examples to start new threads of execution for executing tasks asynchronously. Task
method Run
returns a Task
on which a method can await
the result.