Thread joins : Thread Join « Thread « C# / CSharp Tutorial






using System;
using System.Threading;

class MainClass
{
  private static int ThreadCount = 5;

  public static void DoCount()
  {
    for ( int i = 0; i < 3; i++ )
    {
      System.Console.WriteLine( "{0} reached {1}", Thread.CurrentThread.Name, i );
    }
  }

  [STAThread]
  static void Main(string[] args)
  {
    Thread[] t = new Thread[ ThreadCount ];

    for( int k = 0; k < ThreadCount; k++ )
    {
      t[ k ] = new Thread( new ThreadStart( DoCount ) );
      t[ k ].Name = "Thread " + k;
      t[ k ].Start();
    }

    // wait for all the Threads to finish

    for( int k = 0; k < ThreadCount; k++ )
    {
      t[ k ].Join();
    }
  }
}
Thread 0 reached 0
Thread 0 reached 1
Thread 0 reached 2
Thread 1 reached 0
Thread 1 reached 1
Thread 1 reached 2
Thread 2 reached 0
Thread 2 reached 1
Thread 2 reached 2
Thread 3 reached 0
Thread 3 reached 1
Thread 3 reached 2
Thread 4 reached 0
Thread 4 reached 1
Thread 4 reached 2








20.5.Thread Join
20.5.1.Use Join() to wait for threads to end
20.5.2.Threads Joining
20.5.3.Thread joins
20.5.4.Block until a thread finishes, or timeout after 2 seconds