当所有的线程完成 [英] When All Threads Are Complete

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

问题描述

这是在使用多线程我第一次真正尝试,我想知道什么时候我所有的工作组正在运行完我如何告诉:

 的for(int i = 0; I< taskGroups.Count();我++){
的ThreadStart T = {委托RunThread(taskGroups [I]); };
新的Thread(T)。开始();
}
如果(allThreadsComplete){//?

}



任何帮助将非常感激。



附录:

 的ThreadStart [] =线程新的ThreadStart [taskGroups.Count()]; 
的for(int i = 0; I< taskGroups.Count();我++){
线由[i] =新的ThreadStart []
线由[i] =委托{RunThread(taskGroups [一世]); };
新的Thread(T)。开始();
}
布尔threadsComplete = FALSE;
,而(!threadsComplete){
的for(int i = 0; I< taskGroups.Count();我++){
如果(线程[I] .STATE ==完成)
threadsComplete = TRUE;
}
}


解决方案

您。需要存储所有的线程,然后调用的Thread.join()



事情是这样的:

 列表<螺纹>线程=新的List<螺纹>(); 
的for(int i = 0; I< taskGroups.Count();我++){
INT TEMP = I; //这个修复该问题与我所共享
线程线程=新主题(()=> RunThread(taskGroups [临时]));
threads.Add(螺纹);
thread.Start();
}

的foreach(在线程的线程VAR){
的Thread.join();
}


This is my first real attempt at using multithreading, I want to know how I can tell when all of my tasks groups are done running:

for (int i = 0; i < taskGroups.Count(); i++) {
    ThreadStart t = delegate { RunThread(taskGroups[i]); };
    new Thread(t).Start();
}
if(allThreadsComplete){ //???

}

Any help would be much appreciated

Addendum:

ThreadStart[] threads = new ThreadStart[taskGroups.Count()];
for (int i = 0; i < taskGroups.Count(); i++) {
    threads[i] = new ThreadStart[]
    threads[i] = delegate { RunThread(taskGroups[i]); };
    new Thread(t).Start();
}
bool threadsComplete = false;
while(!threadsComplete){
    for(int i=0;i<taskGroups.Count();i++){
        if(threads[i].State == complete)
        threadsComplete = true;
    }
}

解决方案

You need to store all your threads, and then call Thread.Join().

Something like this:

List<Thread> threads = new List<Thread>();
for (int i = 0; i < taskGroups.Count(); i++) {
   int temp = i; //This fixes the issue with i being shared
   Thread thread = new Thread(() => RunThread(taskGroups[temp]));
   threads.Add(thread);
   thread.Start();
}

foreach (var thread in threads) {
    thread.Join();
}

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

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