gpt4 book ai didi

c# - Csharp 线程在一个完成而不等待加入时启动新线程

转载 作者:行者123 更新时间:2023-11-30 14:16:38 26 4
gpt4 key购买 nike

我搜索了一上午,似乎找不到这个问题的答案。

我有一组线程,每个线程都在工作,然后我将遍历 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() 本质上是这样做的,尽管它还提供了监控和中止等方法,因此可能没有必要在这里重新发明轮子。

关于c# - Csharp 线程在一个完成而不等待加入时启动新线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7141029/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com