A piece of code every day-asynchronous programming (1), asynchronous code programming
How can you let your code do two things at the same time? For example, the UI interface can respond to various click events while initializing and loading configurations. It is not stuck, especially when such a situation occurs, it is very crashing for users.
So what technology should we use to avoid this problem? Yes, asynchronous programming. (Of course, the program is stuck, not necessarily not asynchronously, or the program itself may have exceptions)
Cases
Assume that you are eating breakfast and want to play games at the same time. Now we use code to solve this problem.
First, create a method for eating
1 async static Task <string> EatAsync () 2 {3 Console. writeLine ("Put rice in your mouth"); 4 // This is a very time-consuming operation 5 var result = await Task. run <string> () => 6 {7 for (int I = 0; I <5; I ++) 8 {9 Thread. sleep (500); 10 Console. writeLine ("Chewed under {0}", I); 11} 12 return "swallowed down"; 13}); 14 return result; 15}
In the above code, we can see that the Asynchronous Method requires an async modifier. It is best to end the Asynchronous Method with "Async" as the suffix.
The return values of asynchronous methods are of the following types:
If your method has a return statement of the TResult type with the operand, it is a Task.
If your method does not return a statement or has a return statement without an operand, it is a Task.
If you write an asynchronous event handler, It is Void.
The following describes how to play games (of course, this is only a simple method)
1 // You can also use the Asynchronous Method 2 static void PlayGame () 3 {4 for (int I = 0; I <10; I ++) 5 {6 Thread. sleep (200); 7 Console. writeLine ("Super Mary is running... "); 8} 9}
A simple breakfast Function
1 async static void BreakfastTimeAsync () 2 {3 // return a string type Result 4 Task <string> temp = EatAsync (); 5 6 // do something irrelevant to the meal here 7 PlayGame (); 8 9 // wait for the completion of the temp Task 10 var result = await temp; 11 12 // perform some processing on the final result 13 Console. writeLine (result); 14}
In an asynchronous method, a method usually contains at least one await expression. The expression marks a vertex, at which point, until the waiting Asynchronous Operation completes the method. At the same time, the method is suspended and the control returns to the caller of the method.
Finally, let's look at the running results.
In the end, it is very dangerous to recommend that you do not do other things during dinner.
Reading
Https://msdn.microsoft.com/zh-cn/library/hh191443.aspx
Https://msdn.microsoft.com/zh-cn/library/system.threading.tasks.task%28v=vs.110%29.aspx