如何确定ThreadPool队列中的项目数 [英] How Can I determine the number of items in ThreadPool Queue

查看:95
本文介绍了如何确定ThreadPool队列中的项目数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用ThreadPool来排队1000个工作项

I am using the ThreadPool to queue 1000's of workitems

While(reading in data for processing)
{
    args = some data that has been read;
    ThreadPool.QueueUserWorkItem(new WaitCallback(threadRunner), args);
}

这很好,但是,由于主线程将请求排队的速度快于处理后的内存,因此它被缓慢吞噬.

This is working very well, however, as the main thread queues the requests faster than they are processed memory is slowly eaten up.

我想做一些类似于以下的事情,以随着队列的增加来限制排队

I would like to do something akin to the following to throttle the queueing as the queue grows

Thread.Sleep(numberOfItemsCurrentlyQueued);

随着队列的增加,这将导致更长的等待时间.

This would result in longer waits as the queue grows.

有什么方法可以发现队列中有多少物品?

Is there any way to discover how many items are in the queue?

推荐答案

我不认为有内置的方法,但是您可以引入[static?]计数器来增加或减少它.为此,您必须创建自己的方法来包装ThreadPool.QueueUserWorkItem()并处理计数器.

I don't think there is a built-in way, but you can introduce a [static?] counter that would increase/decrease; for that you would have to create your own method that would wrap ThreadPool.QueueUserWorkItem() and take care of the counter.

顺便说一句,以防万一,如果您正在运行.NET 4.0,则应该使用TaskFactory.StartNew而不是ThreadPool.QueueUserWorkItem()-据说它具有更好的内存/线程管理.

By the way, just in case you are running .NET 4.0, you should use TaskFactory.StartNew instead of ThreadPool.QueueUserWorkItem() - it's said to have better memory/thread management.

这篇关于如何确定ThreadPool队列中的项目数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆