C #~ Asynchronous programming continues ~ Parallel async Asynchronous Method and synchronous method,
Parallel Programming awit & async articles
C # asynchronous programming
I wrote a test code this evening and looked at it again. net's parallel programming, two methods, one is modified by asynchronous async, and the other is a common method. What will happen if I call these two methods in the Main method of the console program?
First, let's take a look at the composition of the method. Step 1 is as follows:
Public async void Step1 () {try {// After await waits, exceptions in the new thread can be caught by the main thread. This is normal and the following code will not be executed by await Task. run () => {Console. writeLine ("Step1 Current ThreadID" + Thread. currentThread. managedThreadId); Thread. sleep (3000) ;}); await Task. run () => {Console. writeLine ("Step1 Current ThreadID" + Thread. currentThread. managedThreadId); Console. writeLine ("ThreadTest. test Runing ") ;}) ;}catch (Exception ex) {Console. writeLine ("ThreadTest" + ex. message );}}
Step 2:
public void Step2() { Console.WriteLine("Step2 Current ThreadID" + Thread.CurrentThread.ManagedThreadId); }
We can see that step 2 is very simple, there is no latency, that is, output a paragraph on the screen, and step 1 is more complicated. It is an Asynchronous Method and uses the Task. run starts two new threads.
The running time of a thread is 3 seconds, which is very long. Haha, the second is to output a paragraph on the screen! What will happen when we write Step 1 and Step 2 together?
Var test = new ThreadTest (); test. Step1 (); // The entire method is not blocked, but the method may block test. Step2 ();
Through the figure above, we realized that,Step 1 is executed first in order, and because the first thread needs to be executed for 3 seconds, step 2 is executed in parallel., 3 seconds later, the second thread of step1 continues to execute (because await is used, so step1 waits internally, it will not ring the method outside of it, it should not ring, hehe!
Why? I read the above example, is it true?Parallel ProgrammingHave a new understanding!