我如何创建多个线程并等待它们全部完成?
这取决于你使用的.NET Framework版本。.NET 4.0使用任务(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()
等待它们完成:
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");
}
我认为你需要使用WaitHandler.WaitAll。这里有一个例子:
public static void Main(string[] args)
{
int numOfThreads = 10;
WaitHandle[] waitHandles = new WaitHandle[numOfThreads];
for (int i = 0; i < numOfThreads; i++)
{
var j = i;
// Or you can use AutoResetEvent/ManualResetEvent
var handle = new EventWaitHandle(false, EventResetMode.ManualReset);
var thread = new Thread(() =>
{
Thread.Sleep(j * 1000);
Console.WriteLine("Thread{0} exits", j);
handle.Set();
});
waitHandles[j] = handle;
thread.Start();
}
WaitHandle.WaitAll(waitHandles);
Console.WriteLine("Main thread exits");
Console.Read();
}
FCL有一些更方便的函数。
(1) Task.WaitAll,以及它的重载函数,用于在并行执行一些任务时(且返回值为空)。
var tasks = new[]
{
Task.Factory.StartNew(() => DoSomething1()),
Task.Factory.StartNew(() => DoSomething2()),
Task.Factory.StartNew(() => DoSomething3())
};
Task.WaitAll(tasks);
(2) Task.WhenAll 适用于想要执行一些带有返回值的任务。它会执行这些操作,并将结果放入一个数组中。它是线程安全的,因此您不需要使用线程安全容器并自己实现添加操作。
var tasks = new[]
{
Task.Factory.StartNew(() => GetSomething1()),
Task.Factory.StartNew(() => GetSomething2()),
Task.Factory.StartNew(() => GetSomething3())
};
var things = Task.WhenAll(tasks);
我写了一个非常简单的扩展方法来等待集合中所有线程:
using System.Collections.Generic;
using System.Threading;
namespace Extensions {
public static class ThreadExtension {
public static void WaitAll (this IEnumerable<Thread> threads) {
if (threads != null) {
foreach (Thread thread in threads) {
thread.Join();
}
}
}
}
}
List<Thread> threads = new List<Thread>();
// Add your threads to this collection
threads.WaitAll();
ThreadHelpers.WaitAll(threadCollection)
.. 无论如何,这基本上是我在测试中使用的。实际代码中我很少需要“等待全部”。 - user2864740Join
,那么你将等待它完成才能启动其他任何线程。你需要先启动 所有 线程,然后 再 Join
所有线程。 - SLaks如果您不想使用 Task 类
(例如在 .NET 3.5 版本中),您可以启动所有线程,然后将它们添加到列表中,在 foreach
循环中调用 join 方法。
例如:
List<Thread> threads = new List<Thread>();
// Start threads
for (int i = 0; i < 10; i++) {
int tmp = i; // Copy value for closure
Thread t = new Thread(() => Console.WriteLine(tmp));
t.Start();
threads.Add(t);
}
// Join threads (wait threads)
foreach (Thread thread in threads) {
thread.Join();
}
我不知道是否有更好的方法,但以下是我使用计数器和后台工作线程的方式。
private object _lock = new object();
private int _runningThreads = 0;
private int Counter{
get{
lock(_lock)
return _runningThreads;
}
set{
lock(_lock)
_runningThreads = value;
}
}
现在每当您创建一个工作线程时,请增加计数器:
var t = new BackgroundWorker();
// Add RunWorkerCompleted handler
// Start thread
Counter++;
在完成工作后,递减计数器:
private void RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
Counter--;
}
if(Couonter>0){
// Some thread is yet to finish.
}
Task.Run()
或Task.Factory.StartNew()
在线程池上实例化我的对象。它们无法正确同步我的长时间运行的委托。Thread.Join()
无法工作。Task.Run()
或Task.Factory.StartNew()
时,要么所有子线程相互阻塞,要么父线程不会被阻塞......我无法通过await
语法的重新序列化来理解如何使用async
委托。using (EventWaitHandle wh = new EventWaitHandle(false, EventResetMode.ManualReset))
{
int outdex = mediaServerMinConnections - 1;
for (int i = 0; i < mediaServerMinConnections; i++)
{
new Thread(() =>
{
sshPool.Enqueue(new SshHandler());
if (Interlocked.Decrement(ref outdex) < 1)
wh.Set();
}).Start();
}
wh.WaitOne();
}
//'arrRunningThreads' = List<Thread>
//Wait for all threads
const int knmsMaxWait = 3 * 1000; //3 sec timeout
int nmsBeginTicks = Environment.TickCount;
foreach(Thread thrd in arrRunningThreads)
{
//See time left
int nmsElapsed = Environment.TickCount - nmsBeginTicks;
int nmsRemain = knmsMaxWait - nmsElapsed;
if(nmsRemain < 0)
nmsRemain = 0;
//Then wait for thread to exit
if(!thrd.Join(nmsRemain))
{
//It didn't exit in time, terminate it
thrd.Abort();
//Issue a debugger warning
Debug.Assert(false, "Terminated thread");
}
}