Detailed explanation of some misunderstandings about async and await
Microsoft's official MSDN says async and await are "asynchronous", but many people (including the author) have some misunderstandings that need to be clarified: why is the await statement not executed after it? Isn't it asynchronous?
An example code is as follows:
Many people (including the author) feel that asynchrony is similar to multithreading at first. When await, a thread will be started in the background to execute tasks, and then the main thread (here is the UI thread) will automatically execute the later part (that is, the message box of "button's event completed" will pop up).
In fact, this understanding is wrong. The essence of async and await is actually the "iterative" waiting of "yield return" and "LINQ". We should be clear: that is, you wrote a LINQ statement:
When you break the breakpoint, you will find that the results will not be executed immediately until the results are used (in the example, here is the foreach). At this time, the Yellow tracking debugging light bar will fold back to var results... Here, and then wait until the results are executed before entering the foreach for execution.
Therefore, async / await and LINQ's "iterative" asynchronous operation are similar. It's just that async / await essentially returns a task, The task is asynchronous (because the task is essentially a thread), so when the method with await is actually executed (when the async method is used), the background will really start a thread to execute the task. At this time, the main thread will wait for the task thread until its execution is completed (the iscomplete property is true). Therefore, the interface will not get stuck.
Therefore, await is just an asynchronous wait for a task, not what we call "asynchronous operation"; Comparing it with LINQ, you will find that the execution sequence of LINQ is the same as it, but LINQ does not wait asynchronously (of course not! It does not start threads...).
We can further compare this:
LINQ: variable = LINQ statement (expression)
Wait until the LINQ variable is used before turning back to the LINQ statement to actually execute the LINQ statement.
Asynchronous wait: variable = asynchronous method
When await + asynchronous method is used, it will turn back to the asynchronous method, start the thread to really execute the asynchronous method, and the main thread will be suspended (but the interface will not die) until the task of the sub thread is completely executed.
In LINQ, if you need to execute immediately, you can use the extension method:
var results = (from …… select ……). ToList(); Because this LINQ statement is used immediately, it will be executed immediately.
Similarly, asynchronous wait can also become synchronous wait like wait:
Because processing originally returns a task, of course, you can also use wait for synchronization.