Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does foreach remove from C# BlockingCollection?

does anyone know if, when iterating on a C# BlockingCollection<>, the elements are taken from the collection, in the same way that BlockingCollection.Take() does for example?

BlockingCollection<int> q = new BlockingCollection<int>();
[...]
foreach(int i in q)
{
    //does q still contain i?
}

Thanks

EDIT: Of course I meant BlockingCollection, but for some reason got BlockingQueue in my head and used that.

like image 447
nitbix Avatar asked Dec 06 '13 11:12

nitbix


People also ask

Can I remove item from list in foreach C#?

You can't use . Remove(element) inside a foreach (var element in X) (because it results in Collection was modified; enumeration operation may not execute.

Which is better for or foreach in C#?

The difference between for and foreach in C# is that for loop is used as a general purpose control structure while foreach loop is specifically used for arrays and collections. In brief, both helps to execute code repeatedly but foreach loop is more specific to arrays and collections.

Can we remove element from ArrayList while iterating C#?

ArrayList provides the remove() methods, like remove (int index) and remove (Object element), you cannot use them to remove items while iterating over ArrayList in Java because they will throw ConcurrentModificationException if called during iteration.


1 Answers

The BlockingCollection<T> enumerator does NOT remove items from the collection.

However, the enumerator returned from BlockingCollection<T>.GetConsumingEnumerable() DOES remove items from the collection.

like image 111
Matthew Watson Avatar answered Oct 02 '22 14:10

Matthew Watson