Thread. Join and Task. Wait methods,
These two methods can be said to be similar functions, both of which are waiting for blocking of the current task and performing subsequent processing after the execution is completed.
Talk is cheap, show you code. The following is asynchronous execution, and the other is blocked. Different execution results can be compared.
1 public static void TaskThreadTest () 2 {3 Stopwatch watch = new Stopwatch (); 4 watch. start (); 5 Thread thread = new Thread (new ThreadStart (ThreadFunction); 6 Console. writeLine ($ "Thread starts"); 7 thread. start (); 8 // thread. join (); 9 watch. stop (); 10 Console. writeLine ($ "Thread time consumed: {watch. elapsedMilliseconds} "); 11 12 Stopwatch watch2 = new Stopwatch (); 13 watch2.Start (); 14 Console. writeLine ($ "Run start"); 1 5 var task = Task. run () => 16 {17 for (int I = 0; I <5; I ++) 18 {19 Thread. sleep (5); 20 Console. writeLine ($ "{I}: Run"); 21} 22}); 23 // task. wait (); 24 watch2.Stop (); 25 Console. writeLine ($ "Run Time: {watch2.ElapsedMilliseconds}"); 26 Console. writeLine ($ "All is End! "); 27 Console. read (); 28} 29 30 public static void ThreadFunction () 31 {32 for (int I = 0; I <5; I ++) 33 {34 Thread. sleep (5); 35 Console. writeLine ($ "{I}: Thread"); 36} 37}
View Code
Observe the running results and we can find that both Thread and Task run in the subthread in asynchronous processing mode.
Next we will release the two comments (Thread. Join and Task. Wait)
Run the job again and observe the results. We can see that the Thread has been merged into the main Thread, blocking the main Thread, and the asynchronous Task of the Task has become the blocking type.
The two methods are easy to use.