创建多个线程,然后等待他们全部完成 [英] Create multiple threads and wait all of them to complete

查看:147
本文介绍了创建多个线程,然后等待他们全部完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么办法解决呢?

推荐答案

这取决于您所使用的.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");
}

这篇关于创建多个线程,然后等待他们全部完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆