我有一个场景,我将不得不启动大量线程(可能多达 100 个),然后等待它们完成,然后执行任务(在另一个线程上)。
进行此类工作的公认模式是什么?只是.Join 吗?还是现在有更高层次的抽象?
在 VS2008 中使用 .NET 2.0。
最佳答案
在 .NET 3.5sp1 或 .NET 4 中,TPL会让这更容易。但是,我将仅针对 .NET 2 功能对其进行调整。
有几个选项。使用 Thread.Join 是完全可以接受的,尤其是当线程都是您手动创建的线程时。这非常容易、可靠且易于实现。这可能是我的选择。
但是,另一种选择是为总工作量创建一个计数器,并在计数器达到零时使用重置事件。例如:
class MyClass {
int workToComplete; // Total number of elements
ManualResetEvent mre; // For waiting
void StartThreads()
{
this.workToComplete = 100;
mre = new ManualResetEvent(false);
int total = workToComplete;
for(int i=0;i<total;++i)
{
Thread thread = new Thread( new ThreadStart(this.ThreadFunction) );
thread.Start(); // Kick off the thread
}
mre.WaitOne(); // Will block until all work is done
}
void ThreadFunction()
{
// Do your work
if (Interlocked.Decrement(ref this.workToComplete) == 0)
this.mre.Set(); // Allow the main thread to continue here...
}
}
关于c# - 等待所有线程完成的有用模式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2291108/