This is all happening in a windows service.
I have a Queue<T>
(actually a ConcurrentQueue<T>
) holding items waiting to be processed. But, I don't want to process only one at a time, I want to process n items concurrently, where n is a configurable integer.
How do I go about doing this using the Task Parallel Library?
I know that TPL will partition collections on behalf of the developer for concurrent processing, but not sure if that's the feature that I'm after. I'm new to multithreading and TPL.
Here is one idea that involves creating an extension method for
TaskFactory
.Then your calling code would look like the following.
Here is another idea using
Parallel.ForEach
. The problem with this approach is that your degrees of parallelism might not necessarily be honored. You are only indicating the maximum amount allowed and not the absolute amount.Use
BlockingCollection<T>
instead ofConcurrentQueue<T>
, then you can start any number of consumer threads and useTake
method of theBlockingCollection
. if the collection is empty, theTake
method will automatically block in the caller thread waiting for items to be added, otherwise the threads will consume all the queue items in parallel. However as your question mentioned out the use of TPL it turns out thatParallel.ForEach
have some issues when using withBlockingCollection
check this post for more details. so you have to manage creation of your consumer threads your self.new Thread(/*consumer method*/)
ornew Task()
...I'd also recommend using a
BlockingCollection
instead of directly using aConcurrentQueue
.Here's an example:
Note that
maxConcurrent
in the constructor defines how many requests will be processed concurrently.