开发者

Thread-safe replacement of ObservableCollection<T> in C# 4.0, with safe enumeration

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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜