c# - 当所有线程都完成时

标签 c# multithreading

这是我第一次真正尝试使用多线程,我想知道如何判断我的所有任务组何时运行完毕:

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

}

任何帮助将不胜感激

附录:

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;
    }
}

最佳答案

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

像这样:

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();
}

关于c# - 当所有线程都完成时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5290006/

相关文章:

c# - 属性 'text'是对象关键信息的一部分,不可修改

c++ - 如何在 cygwin 中使用 boost::thread 编译一个简单的程序?

c - 保证每个线程的执行

c# - Parameterless constructor constructor less 类(来自另一个程序集)

c# - 将 Dapper.net 与 MySql 和 Oracle 结合使用

java - 循环屏障再利用?

c++ - boost group_threads 最大并行线程数

java - 即使没有 volatile ,线程值也不会被线程缓存?

c# - 传递给构造函数的空\null 字符串的更正异常

c# - 如何在 C# 中使用 List 的范围?