Home > Software design >  Search for a particular element in BlockingCollection
Search for a particular element in BlockingCollection

Time:10-20

I have a BlockingCollection:

private readonly BlockingCollection<ImageKeys> myCompletedImages;

I have a method that adds items to the BlockingCollection:

public void addItem(ImageKey theImagekey)
{
    if (this.myCompletedImages.Contains(theImagekey)) // Here it says
                                                      // I do not have "Contains"
    {         
        return;
    }
    this.myCompletedImages.Add(theImagekey);
}

How to know if a particular element is present in a BlockingCollection? Since Contains is not present.. Is there any other way I can do it?

CodePudding user response:

Searching a BlockingCollection<T> to see if it contains a particular element, is a functionality not needed for the intended usage of this class, which is to facilitate producer-consumer scenarios. So this class does not expose a Contains method as part of its public API. You could exploit the fact that the class implements the IEnumerable<T> interface, and use the LINQ Contains operator, however keep in mind this cautionary note from the ConcurrentBag<T> class. AFAIK it applies to all concurrent collections in general:

All public and protected members of ConcurrentBag<T> are thread-safe and may be used concurrently from multiple threads. However, members accessed through one of the interfaces the ConcurrentBag<T> implements, including extension methods, are not guaranteed to be thread safe, and may need to be synchronized by the caller.

(emphasis added)

So you could safely use the LINQ Contains extension method only after the "battle" is over, and all the concurrent operations on the BlockingCollection<T> instance have ended. Which is probably not what you want. In which case the BlockingCollection<T> is probably not the right tool for whatever problem you are trying to solve.

  • Related