.netmultithreadingcollectionsconcurrencyblockingcollection

Element order in BlockingCollection<>


I have a Download Queue implemented with BlockingCollection<>. Now I want to prioritize some Download once in a while. I thought it might be great to move some elements 'up' the Collection, like in a list, but there is no method like Remove()/AddFirst() or Move().

What's the preferred way of arranging items in a BlockingCollection<> ?


Solution

  • BlockingCollection<T> works by wrapping an internal IProducerConsumerCollection<T>. The default is to use a ConcurrentQueue<T> internally, but you can provide your own implementation via this constructor.

    If you provide your own threadsafe collection, you can use any collection type you want. This would allow to you prioritize elements as needed.

    While there are no built-in collections that will implement your desired functionality, you could probably wrap a pair of ConcurrentQueue<T> collections into a class that implements IProducerConsumerCollection<T>. This would allow you to have "high priority" and "low priority" elements.