. NET asynchronous programming first recognized async and await, asyncawait

Source: Internet
Author: User

. NET asynchronous programming first recognized async and await, asyncawait

These are two keywords used for asynchronous programming. Our traditional asynchronous programming methods include Thread, ThreadPool, BeginXXX, and EndXXX. By separating calls and callbacks, the logic of the Code jumps, which may lead to unclear ideas. NET 4.5, the new async and await keywords can help us write asynchronous methods like write synchronous methods (ensure code is neat and clear ).

Let's take a look at an example of a traditional synchronization method:

1 static void Main (string [] args) 2 {3 // synchronization mode 4 Console. WriteLine ("synchronization mode test started! "); 5 SyncMethod (0); 6 Console. WriteLine (" synchronization ended! "); 7 Console. ReadKey (); 8} 9 10 // synchronization operation 11 private static void SyncMethod (int input) 12 {13 Console. WriteLine (" Enter the synchronization operation! "); 14 var result = SyancWork (input); 15 Console. WriteLine (" final result {0} ", result); 16 Console. WriteLine (" Exit synchronization! "); 17} 18 19 // simulate time-consuming operations (synchronization method)
20 private static int SyancWork (int val) 21 {22 for (int I = 0; I <5; ++ I) 23 {24 Console. writeLine ("time-consuming operation {0}", I); 25 Thread. sleep (100); 26 val ++; 27} 28 return val; 29}

The execution result is displayed in the right figure, which is a typical synchronous execution method.

The async keyword can be used in the declaration part of methods and lambda expressions to indicate that this method may contain the await keyword. Only async can use the await keyword internally. An Asynchronous Method can have a return type of Task, Task <>, or void. The await keyword is used in a method or lambda expression whose return value is "awaitable, "awaitable" can be of any type (Common Tasks and tasks <>). It must publish a GetAwaiter () method and return a valid "awaiter ". For more details, refer to the "FAQ on Async and Await", which describes these concepts and precautions.

When an async method contains the await keyword, it will become an Asynchronous Method during compilation. If there is no await keyword, it will only be executed as a synchronization method. If you are interested in its internal implementation, refer to the article "asynchronous performance: Understanding the costs of Async and Await". I believe it is helpful to have a deep understanding of this mechanism.

Now we try to use the new asynchronous keywords async and await to convert them into asynchronous calls:

Static void Main (string [] args)
{// Asynchronous mode Console. WriteLine ("\ n asynchronous mode test started! "); AsyncMethod (0); Console. WriteLine (" End of asynchronous mode! "); Console. ReadKey () ;}// Asynchronous Operation private static async void AsyncMethod (int input) {Console. WriteLine (" Enter asynchronous operation! "); Var result = await AsyncWork (input); Console. WriteLine (" final result {0} ", result); Console. WriteLine (" Exit asynchronous operation! ");} // Simulate time-consuming operations (Asynchronous Method)
Private static async Task <int> AsyncWork (int val) {for (int I = 0; I <5; ++ I) {Console. writeLine ("time-consuming operation {0}", I); await Task. delay (100); val ++;} return val ;}

Let's take a look at the results first. We found that time-consuming operations were performed asynchronously. The overall process is probably to call AsyncMethod asynchronously by the Main function, and continue to execute without waiting for AsyncMethod to complete. However, after the AsyncMethod method is called, it starts to start when it is allocated to the time slice, executes the function body content, and continues to call AsyncWork asynchronously due to the await AsyncWork statement. However, due to the await keyword, wait until the AsyncWork is complete and then proceed. The same is true for AyncWork. After being called, it starts to start when it is allocated to a time slice and performs time-consuming operations.

As you can see, when a new keyword is used, the syntax difference between synchronization and asynchronous programming is further reduced. With. NET 4.5, many new class libraries and existing class libraries support this new asynchronous syntax (such as HttpClient, HttpServer, MemoryStream ...), they use separate methods such as ReadAsync, WriteAsync, and SendAsync to provide asynchronous working methods with async declarations and return types of tasks and tasks.

  Supplement:

A friend mentioned await Task just now. the Delay (100) statement is added to make AsyncWork an asynchronous method. If the operation you want to perform does not support await modification, it is actually very simple to use the Task. factory. startNew () is enough. For example:

1 // Asynchronous Operation 2 private static async void AsyncMethod (int input) 3 {4 Console. WriteLine ("Enter asynchronous operation! "); 5 var result = await Task. factory. startNew (Func <object, int>) SyncWork2, input); 6 Console. writeLine ("final result {0}", result); 7 Console. writeLine ("Exit asynchronous operation! "); 8} 9 10 // simulate time-consuming operations (synchronization method) 11 private static int SyncWork2 (object input) 12 {13 int val = (int) input; 14 for (int I = 0; I <5; ++ I) 15 {16 Console. writeLine ("time-consuming operation {0}", I); 17 Thread. sleep (100); 18 val ++; 19} 20 return val; 21}

In this way, our SyncWork2 is actually executed asynchronously, and the result is the same as that of the previous asynchronous method. In this way, the input parameter can only be of the object type and type conversion is required. In addition to StartNew, we can create a new Task and call Run to achieve the same effect.

Related Article

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.