I have an ObservableCollection<T>
in one of my projects and I need to make access thread-safe.
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?
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:
foreach (var o in myCollection) {
// Do something that takes 10 minutes
}
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:
foreach (var o in myCollection.ToArray()) {
// ...
}
To do this properly, you will need to implement your own ICollection<T>
that takes out a lock in the ToArray
and Add
methods
It might help if you give your requirements or specification more precisely.
ObservableCollection is not thread safe. Implement your own thread safe wrapper over it.
精彩评论