Create multiple threads and wait all of them to complete

前端 未结 8 1936
星月不相逢
星月不相逢 2020-12-02 15:13

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

8条回答
  •  独厮守ぢ
    2020-12-02 15:54

    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");
    }
    

提交回复
热议问题