C#5.0 Asynchronous Programming Async and Await--Introduction

C# 5.0 introduces the async and await keywords to implement asynchronous invocation of methods.

Go straight to the point.

async is just an identifier and has no practical purpose. It is only used to indicate that a method is an asynchronous method. Adding async in front of the method indicates that the method is an asynchronous method, and there will be an await keyword inside the method body. The compiler will give a warning if there is no await keyword.

await is used to wait for the completion of an asynchronous method. The method after await is the asynchronous method. During the execution of the method, after encountering the await keyword, a new thread will be started in the thread pool to execute the method after await. At the same time, a Task object is returned, and the caller thread continues to execute. After the new thread is executed, the method after await will continue to execute to the end of the method and return.

The waiting initiated by await will not cause the thread grouping of the method caller to block. Therefore, it should be called "asynchronous wait", and its behavioral characteristics are similar to those achieved by multi-threaded callbacks.

Here are these two methods, call the TestAsyncInvokeUseAwait method in the main method

The method call stack is as follows

When calling a method asynchronously, the caller will not wait for the called method to finish execution, instead of continuing execution immediately

The execution result is as follows

Here you can see that the DoLongJob method is being executed in the background after the execution... Here, the following statements in the main method are executed immediately; the loop is executed in the background

 Here's a look at the execution flow of an asynchronous call

The code after await can be considered as a whole. It is regarded as the aftermath after completing the data processing task. The function of await is actually the same as the continueWith in TPL.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325070248&siteId=291194637