I would like to know if it is possible to instantiate multiple BlockingCollections with a single backing store for example :
ConcurrentStack<object> theStack = new ConcurrentStack<object>();
BlockingCollection<object> blockingStack1 = new BlockingCollection<object>(theStack);
BlockingCollection<object> blockingStack2 = new BlockingCollection<object>(theStack);
The motivation for this enquiry is as follows; BlockingCollection
requires the invocation of it's Dispose method. This is seamless with the use of a using
block. However, since a using
block is not always appropriate ( consider the producer & consumer living not only in different methods but also on different threads ) trying to do the book-keeping required for calling Dispose becomes a lot less trivial and a lot more error-prone. If however, instead of propagating a BlockingCollection
, you could instead propagate the backing store then a local BlockingCollection
could be instantiated locally inside a using
block.
My guess is that you can since there is nothing in the IProducerConsumerCollection interface, the only thing the BlockingCollection relies on, that seems to imply otherwise.
You can't use multiple BlockingCollection
s with the same IProducerConsumerCollection
safely. Here's some information we have from the MSDN article (which could maybe be taken to mean that you can use more than a single BlockingCollection
):
Do not modify the underlying collection directly. Use BlockingCollection methods to add or remove elements. The BlockingCollection object can become corrupted if you change the underlying collection directly.
We also have the implementation itself here where we see 2 SemaphoreSlim
s being used to bound the BlockingCollection
. We can see that BlockingCollection
wasn't built to support that, and would have to share its internal synchronization objects between the 2 instance to be able to operate correctly.
You don't really need to worry about calling Dispose
twice, but you can simply use a lock around the Dispose
which should only happen once and so is negligible performance wise.