ReadOnlyCollection<T> Thread Safety

C# has a pretty good collection model, but the ReadOnlyCollection class is one of the most unfortunately conceived (or named) classes in the entire model. It should have been more appropriately called a readonly list, not a readonly collection.

Now, to get to your question, it is just a read-only decorator of an IList supplied at construction-time. Therefore, the code which constructed the ReadOnlyCollection may modify the original list, with all the consequences that this will have for multithreaded access.

So, enumerating through the collection would have been thread-safe if the collection was truly readonly; but since it is not read-only, it is not thread safe. Given the amount of reputation that you have, I am pretty sure you are not wondering why enumerating through a non-read-only collection is not thread safe.

As for the workaround that you asked, well, you can either use locking, or you can go with the lock-nothing (or lock-as-little-as-possible) principle and make a true read-only copy of the list.

EDIT

I am re-reading my answer many months later, (thanks to asyncwait's comment,) and I realize that I should have answered all of the OP's questions without making assumptions based on his reputation. The OP has probably received his answer by now, but I will do it for the sake of future readers.

Enumerating through a not-really-read-only collection is intrinsically not thread-safe for the same reasons that even in a single-threaded scenario you cannot modify a collection while enumerating it. (ConcurrentModificationException in Java, InvalidOperationException in C#.) In a single-threaded scenario you can make sure that your enumeration code does not attempt to alter the collection in any way, but in a multi-threaded scenario one thread may be enumerating the collection while another thread may be altering it at the same time.


This MSDN article staes: "An instance of the ReadOnlyCollection generic class is always read-only. A collection that is read-only is simply a collection with a wrapper that prevents modifying the collection"

So I believe iterating is not thread safe as it internally uses a normal non thread-safe collection of objects.

The implications are that different threads might get different values if somehow the collection changes. Use a lock statement to avoid concurrent access to the collection from different threads at the same time.