Cook Computing

Waiting For Multiple Threads in C#

September 11, 2009 Written by Charles Cook

I saw a blog post yesterday which presented a C# class for waiting on multiple threads to terminate. The code was unnecessarily complex and inefficient and so I added a comment on a more efficient way of doing it. Shortly afterwards the post disappeared but in case anyone is wondering the way to do it is simply call Thread.Join() on each of the threads in turn, e.g. if you have a collection of threads:


foreach (Thread t in threads)
    t.Join();

This is my version of the post's sample code:


class Program
{
  static void Main(String[] args)
  {
    var threads = new List<Thread>();
    for (int i = 0; i < 10; i++)
    {
      Thread t = new Thread(name =>
        {
          for (int j = 0; j < 5; j++)
          {
            Console.WriteLine("Thread {0}, Count {1}", name, j);
            Thread.Sleep(500);
          }
          Console.WriteLine("Thread {0} Finished", name);
        });
      threads.Add(t);
      t.Start(i);
    }
    Console.WriteLine("Starting to wait...");
    foreach (Thread t in threads)
      t.Join();
    Console.WriteLine("All threads finished!");
    Console.ReadKey();
  }
}