The newly added async await keyword in. NET Framework 4.5, that is, the Asynchronous Method function, makes the compilation of asynchronous operations very convenient, efficient, and easy to understand. The following is a simple example:
1 Using System; 2 Using System. Collections. Generic; 3 Using System. LINQ; 4 Using System. text; 5 Using System. Threading; 6 Using System. Threading. tasks; 7 8 Namespace Asynctest 9 { 10 Class Program 11 { 12 Static Int Count =0 ; 13 Static Void Main ( String [] ARGs) 14 { 15 Test (); 16 } 17 18 Public Static Async Task test () 19 { 20 List <task < Int > List = New List <task < Int > (); 21 For ( Int I = 0 ; I < 10 ; I ++) 22 { 23 List. Add (get (I + " : " )); 24 } 25 List. Add (get ( " DIS: " )); 26 Console. writeline ( " The last printed content appears at the beginning. " ); 27 Task. waitall (list. toarray ()); 28 Console. Readline (); 29 } 30 31 Public Static Async Task <Int > Get ( String S) 32 { 33 Await Task. Delay ( 100 ); // Await waits for the task. Thread. Sleep let the entire thread wait. 34 Console. writeline (S + datetime. Now. tostring ( " Hh: mm: SS fff " )); 35 Return Count; 36 } 37 } 38 }
Summary:
1) This keyword is also required for the method to be asynchronously executed using the async keyword.
2) The Asynchronous Method returns the task <t>, and the task starts to be executed during the call. However, if await is not used, the call will be executed downward without waiting for the return. The <t> type of return value (taskresult) is saved during the call, so that you can confirm whether the method has been returned.
3) await taskresult; wait (OK) for the method to return.
4) In the example, multiple asynchronous methods are provided to ensure that the execution is completed at the end, and they have been verified to run correctly.