加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – Csharp线程在一个完成而没有等待连接时启动新线程

发布时间:2020-12-16 01:46:47 所属栏目:百科 来源:网络整理
导读:我整个上午都搜索过,似乎无法找到这个问题的答案. 我有一个Threads数组,每个都在做工作,然后我将循环遍历每个开始新线程的ID.什么是检测线程何时完成的最佳方法,这样我可以在不等待每个线程完成的情况下触发新线程? 编辑添加了代码片段也许这会有所帮助 if
我整个上午都搜索过,似乎无法找到这个问题的答案.

我有一个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()基本上做了这个,但是给出了监视和中止等方法,所以可能没有必要在这里重新发明轮子.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读