Search code examples
.netblockingcollection

How to TryPeek on a BlockingCollection based on a ConcurrentStack


I have a BlockingCollection based on a ConcurrentStack:

Dim stackBase As New ConcurrentStack(Of MyObject) Dim myStack = New BlockingCollection(Of MyObject)(stackBase)

In one of my producers I want to check the top item in the blocking collection before adding a new item. I understand the item might be removed by a consumer in the meantime. In this case that isn't a problem because I am just trying to avoid burying certain objects.

The ConcurrentStack has TryPeek which would work perfectly, but I don't have access to the stackBase object.

Any ideas?


Solution

  • You should expose the behavior you are looking for by exposing a service that accesses your concurrent stack and blocking collection. That way you can mock the behavior at test time as well.

    interface IWhateverYourCollectionService {
       //TryPeak();
       //Any other methods that make sense for what your doing.
    }
    

    In this way you could store both of the objects in the service or have them grabbed from a factory and expose the appropriate behavior through your service.