Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to empty a BlockingCollection

Tags:

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?

like image 807
Jon Avatar asked Nov 03 '11 20:11

Jon


2 Answers

I'm using this extension method:

public static void Clear<T>(this BlockingCollection<T> blockingCollection) {     if (blockingCollection == null)     {         throw new ArgumentNullException("blockingCollection");     }      while (blockingCollection.Count > 0)     {         T item;         blockingCollection.TryTake(out item);     } } 

I'm wondering if there's a better, less hacky, solution.

like image 58
Paolo Moretti Avatar answered Sep 30 '22 19:09

Paolo Moretti


Just take out all remaining items:

while (collection.TryTake(out _)){} 
like image 28
mythz Avatar answered Sep 30 '22 20:09

mythz