I don’t know how long your tasks will work, but it seems that ThreadPool will be the best. Moreover, I would use and actually use only one central queue - this in itself will eliminate some complexity. I have one Thread that processes the queue and performs an action on an element in your case, this will be the task queue.
As for creating the queue in streaming mode, there is a ConcurrentQueue in System.Collections.Concurrent for this purpose ( msdn , checkpoint against blocking ).
Now drop the BlockingCollection ( msdn ) and you have everything you need.
BlockingCollection<Packet> sendQueue = new BlockingCollection<Packet>(new ConcurrentQueue<Packet>()); while (true) { var packet = sendQueue.Take(); //this blocks if there are no items in the queue. ThreadPool.QueueUserWorkItem(state => { var data = (Packet)state; //do whatever you have to do }, packet ); }
and somewhere there is something that sendQueue.Add(packet);
Summarizing,
- One turn for all "workers"
- One thread that is removed from the queue and passes it to ThreadPool.
I think that it is.
ps: if you need to control the number of threads, use the "Intelligent Thread Pool" as suggested by josh3736
source share