Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Can I determine the number of items in ThreadPool Queue

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?

like image 274
Perrin255 Avatar asked Dec 10 '10 16:12

Perrin255


People also ask

How do you wait for Threadpool to finish?

You can wait for a task to finish in a ThreadPoolExecutor by calling the wait() module function.

How does the C# Threadpool work?

Thread pooling is the process of creating a collection of threads during the initialization of a multithreaded application, and then reusing those threads for new tasks as and when required, instead of creating new threads.

What is the use of Threadpool QueueUserWorkItem method?

QueueUserWorkItem(WaitCallback, Object) Queues a method for execution, and specifies an object containing data to be used by the method. The method executes when a thread pool thread becomes available.

When using a thread pool What happens to a given thread after it finishes its task?

And it continues showing load after 75% of the threads have completed their job. If 75% of the 500 threads have completed their job then that leaves 100+ threads that continue to run.


1 Answers

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.

like image 102
Steve Townsend Avatar answered Nov 07 '22 03:11

Steve Townsend