从线程池加入线程 [英] Join threads from thread pool
本文介绍了从线程池加入线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有30多个可以并行执行的任务.
我为每个任务使用ThreadPool.
但是在所有任务完成之前,父功能不应该返回.
我需要一个线程同步句柄,当其计数达到0时将释放WaitOne. 像这样:
foo.StartWith(myTasks.Count);
foreach (var task in myTasks) {
ThreadPool.QueueUserWorkItem(state => { task(state); foo.Release(); });
}
foo.WaitOne();
Semaphore
感觉不错,只是不知道如何在此处应用它.
解决方案
int running = myTasks.Count;
AutoResetEvent done = new AutoResetEvent(false);
foreach (var task in myTasks) {
ThreadPool.QueueUserWorkItem(state => {
task(state);
if (0 == Interlocked.Decrement(ref running))
done.Set ();
});
}
done.WaitOne();
在C#4.0中,您可以使用新的 CountdownEvent 原语. /p>
I have 30+ tasks that can be executed in parallel.
I use ThreadPool for each task.
But parent-function should not return until all tasks has completed.
I need a thread sync handle that would release WaitOne when its count reaches 0. Something like:
foo.StartWith(myTasks.Count);
foreach (var task in myTasks) {
ThreadPool.QueueUserWorkItem(state => { task(state); foo.Release(); });
}
foo.WaitOne();
Semaphore
feels right, just can't figure out how to apply it here.
解决方案
int running = myTasks.Count;
AutoResetEvent done = new AutoResetEvent(false);
foreach (var task in myTasks) {
ThreadPool.QueueUserWorkItem(state => {
task(state);
if (0 == Interlocked.Decrement(ref running))
done.Set ();
});
}
done.WaitOne();
With C# 4.0 you can use the new CountdownEvent primitive.
这篇关于从线程池加入线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文