枚举时项目更改是否会影响枚举?

Jad*_*ias 8 .net c# concurrency ienumerable enumeration

想象一下,在一个

foreach(var item in enumerable)
Run Code Online (Sandbox Code Playgroud)

可枚举的项目发生了变化.它会影响当前的foreach吗?

例:

var enumerable = new List<int>();
enumerable.Add(1);
Parallel.ForEach<int>(enumerable, item =>
{ 
     enumerable.Add(item + 1);
});
Run Code Online (Sandbox Code Playgroud)

它将永远循环?

Ken*_* K. 17

通常,它应该抛出异常.List<T>GetEnumerator()的实现提供一个方法如下所示的Enumerator<T>对象MoveNext()(来自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;
}
Run Code Online (Sandbox Code Playgroud)

list._version修改List的每个操作上修改(递增).


Meh*_*ari 5

取决于调查员的性质.当集合发生变化时,其中许多会抛出异常.

例如,如果集合在枚举期间发生更改,则List<T>抛出一个InvalidOperationException.