A Blocking Concurrent Collection - Take method that takes an item that supports a condition

315 Views Asked by At

I would like to have a concurrent collection which supports a blocking thread-safe Take operation, while the actual item taken is an item that satisfies a condition.

Something like:

private TheBlockingCollection<MyClass> _myCollection;

MyClass myItem = _myCollection.TakeItemWhere(item => item.Type.equals(something));

The final goal would be to take the item with the highest property value that currently exists in the collection. e.g. - Max

Is there such a built in collection?

If not, what would be the better alternative?

1

There are 1 best solutions below

1
On BEST ANSWER

As Servy mentions in a comment above, you should use a Priority Queue with a BlockingCollection.

If you implement an appropriate IComparable<> interface for the types being stored in the collection, then when you dequeue items you will automatically get the item that is first according to the comparison interface you defined.

Microsoft have provided a sample ConcurrentPriorityQueue which implements IProducerConsumerCollection that you can use with a BlockingCollection.

You use it by first creating an instance of a ConcurrentPriorityQueue and then by creating the BlockingCollection using one of the constructors which accepts a IProducerConsumerCollection<T>, for example: http://msdn.microsoft.com/en-us/library/dd287133.aspx

You just need to pass the ConcurrentPriortyQueue to that constructor.