Literally answering the question in the title for your question seems academic and not all that useful. Jon has offered some insight as to what a likely answer for that specific question might be. But let's try to address the underlying need you seem to have…
I recently needed an IProducerConsumerCollection implementation but I wanted it to block on TryAdd if a certain capacity has been reached and block on TryTake if it's empty.
These are features that BlockingCollection
already provides. The fact that it doesn't implement IProducerConsumerCollection
isn't an impediment at all, nor does the reason it doesn't implement that interface seem to be relevant to your actual stated need.
- "I wanted it to block on TryAdd if a certain capacity has been reached"
Having the TryAdd()
method block doesn't make any sense. The whole reason for that method is to have a non-blocking add operation (or blocking with a timeout). I.e. to try to perform an add operation, but with the possibility that it might fail.
Instead, initialize the BlockingCollection
with one of the constructors that allows you to pass an int
capacity value, and then use the Add()
method to actually add something to the collection. The Add()
method will block until the collection's current size is less than this capacity.
Note that the TryAdd()
method respects the collection capacity as well; but it treats a full collection as an immediate failure of the add operation. This seems exactly opposite of what you want; i.e. to block until the add operation is assured of success. For that, the Add()
method is definitely the one to use.
- "and block on TryTake if it's empty"
For the same reason that having TryAdd()
block doesn't make sense, nor does having TryTake()
block make sense.
Instead, call GetConsumingEnumerable()
and use the object returned to retrieve items from the collection. If the collection is emptied, the IEnumerable<T>.MoveNext()
method will block until either a new item is added to the collection, or you call the CompleteAdding()
method.
If the above does not address your need, then you should edit your question to explain precisely what it is you do want to accomplish. Even if someone gave you a complete, precise answer to exactly the question you ask in your title, that's not going to help you write any code that actually does something. IMHO, you should focus more on what it is you're trying to do, so that we can help you with that.