当项目同时列举变化的确会影响枚举? [英] When items change while being enumerated does it affects the enumeration?
本文介绍了当项目同时列举变化的确会影响枚举?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
想象一下,在一个
foreach(var item in enumerable)
在枚举的事项发生变化的。它会影响当前的foreach?
The enumerable items change. It will affect the current foreach?
例如:
var enumerable = new List<int>();
enumerable.Add(1);
Parallel.ForEach<int>(enumerable, item =>
{
enumerable.Add(item + 1);
});
它会永远循环下去?
It will loop forever?
推荐答案
一般情况下,它应该抛出一个异常。
该名单,其中,T&GT;
实施的GetEnumerator()提供了一个枚举&LT; T&GT;
对象,其的MoveNext()
方法如下(从反射镜):
Generally, it should throw an exception.
The List<T>
implementation of GetEnumerator() Provides an Enumerator<T>
object whose MoveNext()
method looks like this (from Reflector):
public bool MoveNext()
{
List<T> list = this.list;
if ((this.version == list._version) && (this.index < list._size))
{
this.current = list._items[this.index];
this.index++;
return true;
}
return this.MoveNextRare();
}
private bool MoveNextRare()
{
if (this.version != this.list._version)
{
ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion);
}
this.index = this.list._size + 1;
this.current = default(T);
return false;
}
在 list._version
修改(递增)对每一个修改List操作。
The list._version
is modified (incremented) on each operation which modifies the List.
这篇关于当项目同时列举变化的确会影响枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文