简体   繁体   English

foreach是否从C#BlockingCollection中删除?

[英]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? 有没有人知道,当迭代C#BlockingCollection <>时,是否从集合中获取元素,就像BlockingCollection.Take()所做的那样?

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. 编辑:当然我的意思是BlockingCollection,但由于某种原因,我的头脑中有了BlockingQueue并使用了它。

The BlockingCollection<T> enumerator does NOT remove items from the collection. BlockingCollection<T>枚举器不会从集合中删除项目。

However, the enumerator returned from BlockingCollection<T>.GetConsumingEnumerable() DOES remove items from the collection. 但是,从BlockingCollection<T>.GetConsumingEnumerable()返回的枚举器BlockingCollection<T>.GetConsumingEnumerable() DOES从集合中删除项目。

foreach simply enumerates across a collection. foreach只是枚举整个集合。 It never removes anything from any collection. 它从不删除任何集合中的任何内容。

There is no BlockingQueue<T> in the .NET libraries. .NET库中没有BlockingQueue<T>

Assuming 假设

  1. You're talking about BlockingCollection<T> : No. using foreach calls the GetEnumerator method, which returns an IEnumerator . 你在谈论BlockingCollection<T> :No。使用foreach调用GetEnumerator方法,该方法返回一个IEnumerator Standard implementations of an IEnumerator simply enumerate through the elements in the collection without any observable side effects. IEnumerator标准实现只是简单地枚举集合中的元素,而没有任何可观察到的副作用。 Since MSDN doesn't say otherwise regarding BlockingCollection<T> specifically, it is safe to assume that this specific implementation also has no observable side effects. 由于MSDN没有特别说明BlockingCollection<T> ,因此可以安全地假设此特定实现也没有可观察到的副作用。

  2. You're talking about a third-party library: You'll have to check its implementation, but I think it's safe to assume it doesn't remove anything from the collection. 你在谈论第三方库:你必须检查它的实现,但我认为可以安全地假设它没有从集合中删除任何东西。

Edit : Actually, because BlockingCollection wraps around an IProducerConsumerCollection<T> , BlockingCollection uses the enumerator of the underlying (internal) collection. 编辑 :实际上,因为BlockingCollection包装了IProducerConsumerCollection<T> ,所以BlockingCollection使用底层(内部)集合的枚举器。 None of the IProducerConsumerCollection<T> implementations provided by .NET modify the collection. .NET提供的所有IProducerConsumerCollection<T>实现都不会修改集合。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM