. NET4.5 new features async and await modifier implement asynchronous programming, asyncawait

Source: Internet
Author: User

. NET4.5 new features async and await modifier implement asynchronous programming, asyncawait
Opening

Each version of. net introduces some new features, which allow developers to quickly implement some features. Although the. net version has been updated, the new version is compatible with the old version of the program, at this point Microsoft is doing very well. Every time I learn a new content, the first method of contact is very important in my mind. net multi-Thread programming uses the Thread class, and the program written later will immediately think of using the Thread as long as asynchronous or multi-Thread is used. Although it is known that the asynchronous call of the delegate can also be implemented, however, the Thread class is in front of my mind. At that time, I didn't know the differences and advantages between them, and I didn't know how to choose between them. Arrived. net4.0 introduced the Task class, so we started to implement multi-threaded programming with a small amount of code. From this time on, I began to understand it. net, which of the following asynchronous implementation methods and some internal mechanisms of multithreading are also known for their respective advantages. Net4.5 was also released when it came into contact with the Task class, and brought a more convenient keyword (async, await) to easily Implement Asynchronous function calls. Although I know The async and await modifiers, I am not touched by them, because the use of the Task class in normal work can basically achieve the desired effect. I recently read some source code. Many of the source code uses the async and await keywords to implement Asynchronization, so I also have to learn about it, the use of async and await keywords indeed simplifies the steps required for asynchronous programming in the past, and it is easier to understand. Below are some small examples to illustrate how async and await modifiers implement asynchronous programming and a little different from the previous use of the Task class to implement asynchronous programming. In addition, for more information about asynchronous programming patterns earlier than. net4.0 (included), refer to my other blog post: http://www.cnblogs.com/mingjiatang/p/5267391.html

1 async and await implementation method asynchronous call the following section describes the Asynchronous Method and calling code defined by async, as follows:
Static void Main (string [] args) {AsyncMethod (10); // no.1 Console. writeLine ("execute other things, current Thread id: {0}", Thread. currentThread. managedThreadId); // out.4 Console. readKey ();} static async void AsyncMethod (int I) {Console. writeLine ("Asynchronous Method starts, current Thread id: {0}", Thread. currentThread. managedThreadId); // out.1 await AsyncTaskMethod (I); // No. 3 Console. writeLine ("Exit Asynchronous Method, current Thread id: {0}", Thread. currentThread. managedThreadId); // out.6} public static async Task <int> AsyncTaskMethod (int I) {Console. writeLine ("[task] Start, current Thread id: {0}", Thread. currentThread. managedThreadId); // out.2 Task <int> t = Task. run () => {Console. writeLine ("[task] is being executed. The Thread id of the task to be executed: {0}", I, Thread. currentThread. managedThreadId); // out.3 Thread. sleep (2000); return I;}); // No. 4 int r = await t; // No. 5 Console. writeLine ("[task] execution completed, current Thread id: {0}", I, Thread. currentThread. managedThreadId); // out.5 return r ;}

The execution result is as follows:

---------------- The syntax of async and await is combined with the code ------------------ before interpreting the program's execution principle, we will introduce the key syntaxes of async and await. async can only modify methods, lambda expressions, or anonymous methods, await is usually used before a Task or a Task <TResult> object to wait for the Task to complete. ----------------- Explain the Program Execution Process ------------------------------------- 1. The Main thread [9] enters the Main method and executes the no.1 Asynchronous Method. 2. The main thread [9] enters the Asynchronous Method AsyncMethod and runs out.1. 3. The main thread [9] executes the No. 3 asynchronous task method. Because the await keyword in front of the expression No. 3 is modified, out.6 is executed only after the task is completed. 4. The main thread [9] enters the AsyncTaskMethod of the asynchronous task method and runs out2. 5. Start the Task execution. The program obtains a Task thread [10] From the thread pool to execute the Task No. 4. 6. The task thread [10] starts the task and executes out.3. 7. When the thread [10] executes the task, the main thread [9] runs synchronously. When the task is executed to No. 5, when the await keyword is encountered, it will wait until the task is completed and the following out.5 will not be executed. Therefore, the Main line returns to the Main method and runs out.4. At this point, the Main thread code has been executed. 8. The task thread [10] completes the execution of the task, then executes the code out.5 after No. 5, and finally returns the execution result of the task. 9. At this time, the task No. 3 has been waiting for has been executed, and a thread [6] is started from the thread pool to call the code after No. 3. 10. The entire program has been executed. Summary The asynchronous Implementation of async and await keywords is still using threads in the thread pool. I personally think that the internal implementation is implemented using the Task class, but the callback at the end of the Task is simpler than using the Task independently. When you use the Task class to implement Asynchronization separately, when the Task is completed, you need to call the ContinueWith method on the Task object, bind the callback function after the Task is completed, and pass related parameters. When async and await are used for asynchronous implementation, you only need to use the Task to execute the Task, and then use await to wait for the result of the Task to be executed, without blocking the running of the main thread, the entire coding process is similar to synchronous implementation. This example is a good example. ------------------------------ Finally, describe the key points and functions of async and await ------------------------------------------
1. asynchronous methods (including anonymous methods and lambda expressions) must be modified Using async. 2. asynchronous methods can have return-type void, Task, or Task <TResult>. This method cannot declare any ref or outbound parameters, although it can call methods with such parameters. When the returned value is TRsult, the return type is Task <TResult>. 3. The await operator is applied to the task suspension method of An Asynchronous Method until the task is completed. Task indicates a job in progress. 4. The await expression does not block the thread that calls it. When the task is completed, it will call its continuation task, and the asynchronous method will resume the position where it will stop. In other words, await allows the current method to wait until the Task is executed.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.