我将最大线程设置为 10。然后我使用 ThreadPool.QueueUserWorkItem 添加了 22000 个任务。
运行程序后很可能没有完成所有22000个任务。可用线程排队的任务数量是否有限制?
如果您需要等待所有任务处理完毕,则需要自己处理。 ThreadPool 线程都是后台线程,不会使应用程序保持活动状态。
这是处理此类情况的相对干净的方法:
using (var mre = new ManualResetEvent(false))
{
int remainingToProcess = workItems.Count(); // Assuming workItems is a collection of "tasks"
foreach(var item in workItems)
{
// Delegate closure (in C# 4 and earlier) below will
// capture a reference to 'item', resulting in
// the incorrect item sent to ProcessTask each iteration. Use a local copy
// of the 'item' variable instead.
// C# 5/VS2012 will not require the local here.
var localItem = item;
ThreadPool.QueueUserWorkItem(delegate
{
// Replace this with your "work"
ProcessTask(localItem);
// This will (safely) decrement the remaining count, and allow the main thread to continue when we're done
if (Interlocked.Decrement(ref remainingToProcess) == 0)
mre.Set();
});
}
mre.WaitOne();
}
话虽这么说,如果您有数千个工作项,通常最好将它们“分组”在一起,而不是将它们视为线程池的单独工作项。这是管理项目列表所涉及的一些开销,并且由于您无法一次处理 22000 个项目,因此最好将它们分组为块。每个进程有 50 个左右的单个工作项目可能会对您的整体吞吐量有很大帮助......
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)