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的每个操作上修改(递增).
归档时间: |
|
查看次数: |
4173 次 |
最近记录: |