I have a thread adding items to a BlockingCollection
.
On another thread I am using
foreach (var item in myCollection.GetConsumingEnumerable())
If there is a problem I want to break out of my foreach and my method and clear whatever is left in the BlockingCollection
however I can't find a way to do it.
Any ideas?
I'm using this extension method:
I'm wondering if there's a better, less hacky, solution.
Just take out all remaining items:
Possibly use the overload of
GetConsumingEnumerable
which takes aCancellationToken
, and then if anything goes wrong from the producing side, it can cancel the consumer.I assumed you mean clear your blocking collection. Jon's answer is more appropriate to your actual question I think.
This worked for me
Take()
removes from the collection and you can call any clean up on your object and the loop condition does not invoke any blocking calls.For just clearing the collection you can do:
or just