我整个上午都搜索过,似乎无法找到这个问题的答案.
我有一个Threads数组,每个都在做工作,然后我将循环遍历每个开始新线程的ID.什么是检测线程何时完成的最佳方法,这样我可以在不等待每个线程完成的情况下触发新线程?
if (threadCount > maxItems) { threadCount = maxItems; } threads = new Thread[threadCount]; for (int i = 0; i < threadCount; i++) { threads[i] = new Thread(delegate() { this.StartThread(); }); threads[i].Start(); } while (loopCounter < threadCount) { if (loopCounter == (threadCount - 1)) { loopCounter = 0; } if (threads[loopCounter].ThreadState == ThreadState.Stopped) { threads[loopCounter] = new Thread(delegate() { this.StartThread(); }); threads[loopCounter].Start(); } }
解决方法
而不是每次都创建新的线程,为什么不让每个线程调用一个函数来返回下一个ID(如果没有更多的数据要处理,则返回null)当它完成当前的一个?该函数显然必须是线程安全的,但是应该减少你的开销,而不是观察完成的线程并开始新的线程.
所以,
void RunWorkerThreads(int threadCount) { for (int i = 0; i < threadCount; ++i) { new Thread(() => { while(true) { var nextItem = GetNextItem(); if (nextItem == null) break; /*do work*/ } }).Start(); } } T GetNextItem() { lock(_lockObject) { //return the next item } }
我可能会拉出GetNextItem并“运行”并将它们作为参数传递给RunWorkerThreads以使其更通用 – 因此它将是RunWorkerThreads< T>(int count,Func< T> getNextItem,Action< T> workDoer ),但这取决于你.
请注意,Parallel.ForEach()基本上做了这个,但是给出了监视和中止等方法,所以可能没有必要在这里重新发明轮子.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。