Thread. Join and Task. Wait methods,

Source: Internet
Author: User

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.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.