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

编程入门 行业动态 更新时间:2024-10-28 17:28:27
本文介绍了如何确定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队列中的项目数

本文发布于:2023-10-26 20:31:47,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1531268.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:队列   项目   ThreadPool

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!