有没有更好的方法在执行另一个进程之前等待排队的线程?
目前我在做:
this.workerLocker = new object(); // Global variable
this.RunningWorkers = arrayStrings.Length; // Global variable
// Initiate process
foreach (string someString in arrayStrings)
{
ThreadPool.QueueUserWorkItem(this.DoSomething, someString);
Thread.Sleep(100);
}
// Waiting execution for all queued threads
lock (this.workerLocker) // Global variable (object)
{
while (this.RunningWorkers > 0)
{
Monitor.Wait(this.workerLocker);
}
}
// Do anything else
Console.WriteLine("END");
// Method DoSomething() definition
public void DoSomething(object data)
{
// Do a slow process...
.
.
.
lock (this.workerLocker)
{
this.RunningWorkers--;
Monitor.Pulse(this.workerLocker);
}
}
最佳答案
您可能想看看 AutoResetEvent 和 ManualResetEvent。
这些正是针对这种情况(在执行“某事”之前等待 ThreadPool 线程完成)。
你会做这样的事情:
static void Main(string[] args)
{
List<ManualResetEvent> resetEvents = new List<ManualResetEvent>();
foreach (var x in Enumerable.Range(1, WORKER_COUNT))
{
ManualResetEvent resetEvent = new ManualResetEvent();
ThreadPool.QueueUserWorkItem(DoSomething, resetEvent);
resetEvents.Add(resetEvent);
}
// wait for all ManualResetEvents
WaitHandle.WaitAll(resetEvents.ToArray()); // You probably want to use an array instead of a List, a list was just easier for the example :-)
}
public static void DoSomething(object data)
{
ManualResetEvent resetEvent = data as ManualResetEvent;
// Do something
resetEvent.Set();
}
编辑:忘记提及您可以等待单个线程、任何线程等等。 同样根据您的情况,AutoResetEvent 可以稍微简化一些事情,因为它(顾名思义)可以自动发出事件信号 :-)
关于c# - 有没有更好的方法来等待排队的线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1045980/