Parallel Programming Awit&async related articles
C # Asynchronous programming
It's all right tonight. Write a test code, and look at. NET parallel programming, two methods, one is asynchronous async modification, the other is a common method, in the console program's main method to call these two methods, what will be the result?
First we look at the composition of the method, Step1 as follows
Public Async voidStep1 () {Try { //after the await waits, the new thread's exception can be captured by the main path, which is normal, and the following code will not be executed awaitTask.run (() ={Console.WriteLine ("Step1 Current ThreadID"+Thread.CurrentThread.ManagedThreadId); Thread.Sleep ( the); }); awaitTask.run (() ={Console.WriteLine ("Step1 Current ThreadID"+Thread.CurrentThread.ManagedThreadId); Console.WriteLine ("threadtest.test runing"); }); } Catch(Exception ex) {Console.WriteLine ("ThreadTest"+Ex. Message); } }
Step2 as follows
Public void Step2 () { Console.WriteLine ("Step2 current ThreadID" + Thread.CurrentThread.ManagedThreadId); }
We can see that Step2 is very simple, there is no delay, is to output a paragraph on the screen, and Step1 is more complicated, it is an asynchronous method, and use Task.run to open two new threads, and the first
The running time of a thread is 3 seconds, very long, haha, the second one is to output a paragraph on the screen! Now what happens when we write Step1 and Step2 together?
var New threadtest (); test. Step1 (); // the entire method is not blocked, but the method may block test inside . STEP2 ();
From the above figure we realize thatStep1 executes first in order, and because the first thread executes for 3 seconds, then STEP2 is executed in parallel , and after 3 seconds, the second thread of STEP1 continues to execute (because the await is used, the Step1 internally waits, Should not ring his outside method, also should not ring, hehe!
What, look at the above for example, is not the parallel programming has a new understanding of it!
C#~ asynchronous programming and continuation ~async asynchronous method and synchronous method parallel