等到所有的线程在线程池完成其工作 [英] Wait until all threads finished their work in ThreadPool

查看:111
本文介绍了等到所有的线程在线程池完成其工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var list = new List<int>();
for(int i=0;i<10;i++) list.Add(i); 
for(int i=0;i<10;i++)
{
     ThreadPool.QueueUserWorkItem(
         new WaitCallback(x => {
             Console.WriteLine(x);  
         }), list[i]);
} 

和我想知道,当所有的线程池线程完成自己的工作。我该怎么做呢?

And i want to know when all threadpools threads finished their work. How i can to do that?

推荐答案

您需要跟踪此自己。

这个问题的一个方法是使用一个计数器和一个复位事件:

One option for this is to use a counter and a reset event:

int toProcess = 10;
using(ManualResetEvent resetEvent = new ManualResetEvent(false))
{
    var list = new List<int>();
    for(int i=0;i<10;i++) list.Add(i); 
    for(int i=0;i<10;i++)
    {
        ThreadPool.QueueUserWorkItem(
           new WaitCallback(x => {
              Console.WriteLine(x);  
              // Safely decrement the counter
              if (Interlocked.Decrement(ref toProcess)==0)
                 resetEvent.Set();

           }),list[i]);
    } 

    resetEvent.WaitOne();
}
// When the code reaches here, the 10 threads will be done
Console.WriteLine("Done");

这篇关于等到所有的线程在线程池完成其工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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