read the table of contents:Basic theory Analysis Internal Realization analysis key attention of local summary
Basic Introduction
Async, await is the new asynchronous programming method net4.x, which is designed to simplify the writing of asynchronous programs, as compared to the previous APM methods.
APM mode, BeginGetRequestStream needs to pass in the callback function, the thread will continue to execute the following logic in non-blocking form when it encounters BeginXxx, and then callback the previously passed function.
HttpWebRequest Myreq = (HttpWebRequest) webrequest.create ("http://cnblogs.com/");
Myreq.begingetrequeststream ();
Todo
Async way, using the async tag Async1 as an asynchronous method, the await tag getrequeststreamasync represents a time-consuming operation within the method. The main thread returns immediately when it encounters await and continues to execute the logic below the main thread in non-blocking form. When the await time consuming operation completes, continue to execute the logic below ASYNC1
static async void Async1 ()
{
HttpWebRequest myreq = (HttpWebRequest) webrequest.create ("http://cnblogs.com/") ;
await Myreq.getrequeststreamasync ();
To do
}
The above is an asynchronous implementation of the Net class library, if you want to implement your own method.
APM Mode:
public delegate int MyDelegate (int x);
MyDelegate Mathdel = new MyDelegate ((a) => {return 1;});
Mathdel.begininvoke (1, (a) => {},null);
Async Way:
static async void Async2 ()
{
await Task.run (() => {thread.sleep (500); Console.WriteLine ("BBB"); });
Console.WriteLine ("CCC");
}
Async2 ();
Console.WriteLine ("AAA");
In contrast, async/await is very simple and graceful, the amount of code required to write is less, more in line with people writing habits.
because the human mind is better understood by the linear step.
The implementation steps of the APM asynchronous callback are: A logic-> false C callback logic->b logic-> true C callback logic, which in some degree causes confusion of thinking, when a large number of asynchronous callback in a project, it becomes difficult to maintain.
The addition of Async and await to the original chaotic steps, the following steps are: A logic->b logic->c logic. Fundamental Analysis
As a programmer of self cultivation, inquisitive curiosity is very important. Async just come out will let people have confused feeling, how await directly returned, Microsoft How to out a new set of asynchronous model. That's because you're accustomed to the previous APM Non-linear approach, and now it's not easy to get back to the linear steps. Learn Async time, you can use the existing APM way to understand that the following code is purely fictitious .
For example, the Async3 method that Async2 the way to visualize APM:
static async void Async3 ()
{
var task= await Task.run (() => {thread.sleep (500); Console.WriteLine ("BBB"); });
Callback task after the registration task completes
. Registercompletedcallback (() =>
{
Console.WriteLine ("CCC");
}
It is better to understand the above, then the Async3 method to imagine the Async4 method:
static void Async4 ()
{
var thread = new Thread (() =>
{
thread.sleep);
Console.WriteLine ("BBB");
Callback thread after registering thread completion
. Registercompletedcallback (() =>
{
Console.WriteLine ("CCC");
});
Thread. Start ();
}
This looks very simple and clear, even async have been removed, become familiar with the programming habits. Although the code is fictitious, the basic idea is interlinked, the difference lies in the implementation of the details above. Internal Implementation Analysis
As a programmer of self-cultivation, rigorous is not less attitude. Although the basic idea above is good to understand, but the specific details, programming is a does not allow the slightest false work, the fictitious code completely sorry to reader ah.
To continue looking at the Async2 method, the complete code to decompile is as follows: View code
found that async, await disappeared, but also the compiler level to provide the syntax of sugar optimization, so that async is not a completely new asynchronous model. It can be understood that async is more of a regression of linear execution steps, specifically designed to simplify asynchronous code writing.
From the decompile code, we can see that the compiler is reborn into an inherited iasyncstatemachine state machine structure ASYNCD (called <async2>d__2 in the code, followed by a shorthand ASYNCD), which is analyzed based on the decompile code. .
Iasyncstatemachine the most basic state machine interface definition:
Public interface Iasyncstatemachine
{
void MoveNext ();
void Setstatemachine (Iasyncstatemachine statemachine);
}
Since there is no impediment to async, await grammatical sugars, the code execution process can be understood in a linear order, and the entire execution steps are as follows:
1. Main thread call ASYNC2 () method
2. The Async2 () method initializes the state machine state to 1, starting the ASYNCD
3. The MoveNext method starts inside, and its Task.run function throws the task into the thread pool, returning a handle to the waiting task. MoveNext Source Analysis:
Delegate to perform the task
program.cs$<>9__cachedanonymousmethoddelegate1 = new Action (PROGRAM.<ASYNC2>B__0);
Starting with a task to do asynchronous is a net4.0 programming approach based on tasks.
Awaiter =task.run (program.cs$<>9__cachedanonymousmethoddelegate1). Getawaiter ();
Set the state to 0 to MoveNext the direct break again, executing the logic behind the switch, typical state machine mode.
this.<>1__state = 0;
Returns the thread that called the Async2 method, allowing it to continue to perform the logic behind the main thread
This.<>t__builder. Awaitunsafeoncompleted<taskawaiter, program.<async2>d__2> (ref awaiter, ref this);
Return
4. At this time, there are already 2 threads running, respectively, the main thread and Task.run in the running task threads.
5. Following the main thread, the logical output is AAA, the output of BBB after the task thread is completed, and the business logic output CCC after continuing the task thread.
label_0090:
awaiter. GetResult ();
Awaiter = new Taskawaiter ();
Console.WriteLine ("CCC");
This can be understood as async the entire main thread synchronization logic, split into two pieces. The first block is executed directly in the main thread, and the second is executed after the task thread completes, and the middle of the two block is the task thread running and awaiter in the source code. GetResult () executes the second block after waiting for the task thread to complete.
From the consumer's point of view, the execution step is: Main Thread A logic-> asynchronous task Threads B logic-> main thread C logic.
Test ();
Console.WriteLine ("A Logic");
static async void Test ()
{
await task.run () => {thread.sleep (1000); Console.WriteLine ("B Logic"); });
Console.WriteLine ("C Logic");
}
Back to the comparison of the basic principles of the analysis of the fictional method Async4 (), found that the difference is that one is completed after the callback, one is waiting to be completed after the execution, which is the most basic way to achieve asynchronous two broad categories. places to focus attention main Thread A logic-> asynchronous task Threads B logic-> main thread C logic.
Note: These 3 steps are likely to use the same thread or 2 or even 3 threads. Can be learned by Thread.CurrentThread.ManagedThreadId test.
Async7 ();
Console.WriteLine (Thread.CurrentThread.ManagedThreadId);
static async void Async7 ()
{
await task.run () =>
{
Console.WriteLine ( Thread.CurrentThread.ManagedThreadId);
};
Console.WriteLine (Thread.CurrentThread.ManagedThreadId);
}
Precisely because of this, will have the speech said async not to have the thread, also has said needs the thread, from the single aspect is right, also is wrong. The above source code is simple analysis, specific async internal will involve thread context switch, thread multiplexing, scheduling and so on. Want to delve into the classmate can study under Executioncontextswitcher, SECURITYCONTEXT.RESTORECURRENTWI, ExecutionContext these several dongdong.
In fact, the specific physical thread details can not be too concerned about, know its "main thread a logic-> asynchronous task thread B logic-> The main thread C logic" This basic principle can be. In addition, Async will be wired overhead, so it is reasonable to use the business scene. Summary
From the gradual analysis of the async found that NET provides asynchronous way basically in the same vein, such as:
1. net4.5 's async, the grammatical sugar is the Net4.0 task+ state machine.
2. net4.0 task, degradation to 3.5 is (Thread, ThreadPool) + implementation of the wait, cancel and other API operations.
This article takes the async as the starting point, the simple analysis its internal principle and the realization, hoped has the help to everybody.