ObservableCollection的线程安全替换在 C# 4.0 中,具有安全枚举
我的一个项目中有一个 ObservableCollection
,我需要使访问成为线程安全的。
特别是,我需要一个线程安全的枚举器。这意味着,在迭代集合期间(例如在 LINQ 查询期间),任何人都不应该能够添加项目。
我注意到 .NET 4.0 命名空间 System.Collections.Concurrent 中的类。然而,它们似乎都不匹配。另外,在 MSDN 文档 中,我没有找到关于以下内容的段落:访问实际上是线程安全的。
某处是否存在我可以使用的现有线程安全集合,或者我必须自己实现它?
I have an ObservableCollection<T>
in one of my projects and I need to make access thread-safe.
In particular, I need to have a thread-safe enumerator. This means, during iterating over the collection (e.g. during a LINQ query), no one should be able to add an item.
I noticed the classes in the .NET 4.0 namespace System.Collections.Concurrent
. However none of them seems to match. Plus, in the MSDN doc, I did not find a paragraph about which accesses actually are thread-safe.
Is there an existing thread-safe collection somewhere, that I can use, or must I implement that myself?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
请记住,如果您在
GetEnumerator
方法中取出锁,您可能会持有锁很长时间,在此期间没有人能够向您的集合添加对象:您还需要考虑如果多个迭代同时发生会发生什么。这意味着某种 MRSW 锁(多读单写),您可能必须自己实现。
听起来您实际上需要做的是迭代集合的快照:
要正确执行此操作,您将需要实现自己的
ICollection
来获取ICollection
中的锁。 code>ToArray 和Add
方法如果您更准确地给出您的要求或规范,这可能会有所帮助。
Bear in mind that if you take out a lock in the
GetEnumerator
method, you could be holding a lock for a very long time, during which time no one will be able to add objects to your collection:You also need to think about what happens if multiple iterations are happening at the same time. That means some sort of MRSW lock (multiple reader single writer), which you might have to implement yourself.
It sounds like what you actually need to do is to iterate over a snapshot of the collection:
To do this properly, you will need to implement your own
ICollection<T>
that takes out a lock in theToArray
andAdd
methodsIt might help if you give your requirements or specification more precisely.
ObservableCollection 不是线程安全的。在其上实现您自己的线程安全包装器。
ObservableCollection is not thread safe. Implement your own thread safe wrapper over it.