Search code examples
c#.netmultithreading

Create multiple threads and wait for all of them to complete


How can I create multiple threads and wait for all of them to complete?


Solution

  • It depends which version of the .NET Framework you are using. .NET 4.0 made thread management a whole lot easier using Tasks:

    class Program
    {
        static void Main(string[] args)
        {
            Task task1 = Task.Factory.StartNew(() => doStuff());
            Task task2 = Task.Factory.StartNew(() => doStuff());
            Task task3 = Task.Factory.StartNew(() => doStuff());
    
            Task.WaitAll(task1, task2, task3);
                    Console.WriteLine("All threads complete");
        }
    
        static void doStuff()
        {
            //do stuff here
        }
    }
    

    In previous versions of .NET you could use the BackgroundWorker object, use ThreadPool.QueueUserWorkItem(), or create your threads manually and use Thread.Join() to wait for them to complete:

    static void Main(string[] args)
    {
        Thread t1 = new Thread(doStuff);
        t1.Start();
    
        Thread t2 = new Thread(doStuff);
        t2.Start();
    
        Thread t3 = new Thread(doStuff);
        t3.Start();
    
        t1.Join();
        t2.Join();
        t3.Join();
    
        Console.WriteLine("All threads complete");
    }