I wait for available items in two BlockingCollections
in a loop using BlockingCollection.TakeFromAny
. Items are added to the collections in other theads. At some point I finish adding to the collections and on the next call to TakeFromAny
my code gets stuck and does not return from it.
I tried to use CompleteAdding
for the two collections or use TakeFromAny
with a CancellationToken
parameter but in both cases an exception occurs:
- with
CompleteAdding
there is anArgumentException
with the message
All collections are marked as complete with regards to additions. Parameter name: collections
- with
CancellationToken
there is anOperationCanceledException
obviously.
Is it possible to set collections in some way that my code gets out from TakeFromAny without an exception and with a return value that would indicate that there won't be any new items in the underlying collections?
TryTakeFromAny
is not suitable for my needs as it always returns when it happens that the collections are currently empty but items still will be added later. I want to block until the next item is available or there is nothing to add.