创建多个线程,然后等待他们全部完成多个、线程、全部

2023-09-02 23:47:13 作者:眉蹙秋波

什么办法解决呢?

推荐答案

这取决于您所使用的.NET Framework的版本。 .NET 4.0使得线程管理更简单。使用任务一大堆:

It depends which version of the .NET Framework you are using. .NET 4.0 makes 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
    }
}

在.NET中,你可以使用BackgroundWorker的对象,请使用ThreadPool.QueueUserWorkItem(),或手动创建线程和使用的Thread.join()的previous版本,以等待它们完成:

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