如何确定 ThreadPool 队列中的项目数

发布于 2024-10-07 01:08:51 字数 431 浏览 5 评论 0原文

我正在使用 ThreadPool 对 1000 个工作项进行排队。

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

然而,这工作得很好,因为主线程对请求进行排队的速度比处理请求的速度快,内存慢慢被耗尽。

我想做类似于以下的事情来随着队列的增长而限制排队。随着队列的增长,

Thread.Sleep(numberOfItemsCurrentlyQueued);

这将导致更长的等待时间。

有没有办法知道队列中有多少项目?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

め可乐爱微笑 2024-10-14 01:08:51

生产者/消费者队列的更易于管理的抽象是 BlockingCollection。那里的示例代码展示了如何使用任务来播种和排出队列。队列计数可以通过 Count 属性轻松获得。

如果可以,请避免使用Sleep来延迟更多物品的生产。当队列变得太大时,让生产者等待事件或类似事件,并在队列积压达到允许生产更多项目的阈值时让消费者发出事件信号。总是尝试让事情由事件驱动 - Sleep 有点猜测。

A more manageable abstraction for Producer/Consumer queue is BlockingCollection<T>. The example code there shows how to use Tasks to seed and drain the queue. The queue count is readily available via the Count property.

If you can, avoid using Sleep to delay production of more items. Have the producer wait on an Event or similar when queue gets too large, and have consumer(s) signal the Event when the queue backlog reaches a threshold where you are comfortable allowing more items to be produced. Always try to make things event-driven - Sleep is a bit of a guess.

月下伊人醉 2024-10-14 01:08:51

我不认为有内置的方法,但你可以引入一个会增加/减少的[静态?]计数器;为此,您必须创建自己的方法来包装 ThreadPool.QueueUserWorkItem() 并处理计数器。

顺便说一句,以防万一您运行的是 .NET 4.0,您应该使用 TaskFactory.StartNew 而不是 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.

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文