在 C# Collections 库中是否存在修改结构不会使迭代器失效的数据结构?
考虑以下几点:
List<int> myList = new List<int>();
myList.Add( 1 );
myList.Add( 2 );
List<int>.Enumerator myIter = myList.GetEnumerator();
myIter.MoveNext(); // myIter.Current == 1
myList.Add( 3 );
myIter.MoveNext(); // throws InvalidOperationException
最佳答案
是的,看看 System.Collections.Concurrent
.NET 4.0 中的命名空间。
请注意,对于此命名空间中的某些集合(例如 ConcurrentQueue<T>
),这仅通过在相关集合的“快照”上公开枚举器来工作。
来自 the MSDN documentation on ConcurrentQueue<T>
:
The enumeration represents a moment-in-time snapshot of the contents of the queue. It does not reflect any updates to the collection after GetEnumerator was called. The enumerator is safe to use concurrently with reads from and writes to the queue.
不过,并非所有系列都如此。 ConcurrentDictionary<TKey, TValue>
,例如,为您提供一个枚举器,该枚举器在调用 MoveNext
之间维护对基础集合的更新。 .
来自 the MSDN documentation on ConcurrentDictionary<TKey, TValue>
:
The enumerator returned from the dictionary is safe to use concurrently with reads and writes to the dictionary, however it does not represent a moment-in-time snapshot of the dictionary. The contents exposed through the enumerator may contain modifications made to the dictionary after GetEnumerator was called.
如果您没有 4.0,那么我认为其他人是对的,.NET 没有提供这样的集合。但是,您始终可以通过做同样的事情来构建自己的 ConcurrentQueue<T>
确实(遍历快照)。
关于c# - 是否有修改不会使迭代器失效的 C# 集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2753724/