Rui Ruivo

Rui Ruivo

  • NA
  • 132
  • 37.2k

Threading - t.Join() - What does it do exactly?

Apr 12 2018 4:11 PM
Hello
 
I am deepening my understanding of the c# language and trying to really understand all the little details.
I have the following code in wish i cannot understand the difference in using t.Join() .
Can anyone help me ?
  1. using System;  
  2. using System.Threading;  
  3.   
  4. namespace _70483  
  5. {  
  6.     public static class Program  
  7.     {  
  8.         public static void ThreadMethod()  
  9.         {  
  10.             for (int i = 0; i<10; i++)  
  11.             {  
  12.                 Console.WriteLine("ThreadProc: {0}", i);  
  13.                 Thread.Sleep(0);  
  14.             }  
  15.         }  
  16.         static void Main(string[] args)  
  17.         {  
  18.             Thread t = new Thread(new ThreadStart (ThreadMethod));  
  19.             t.Start();  
  20.   
  21.             for (int i = 0; i< 4 ; i++)  
  22.             {  
  23.                 Console.WriteLine("Main thread: Do some work.");                    
  24.                 Thread.Sleep(0);  
  25.             }  
  26.             t.Join(); // Method is called on the main thread to let it wait until the other thread fnishes.  
  27.             Console.ReadLine();  
  28.         }  
  29.   
  30.     }  
  31. }  
I have tryed to remove it and cannot see any difference.
Is it maybe because i have Thread.Sleep(0) ?
 
Best regards
Rui 

Answers (2)