In multi-threaded scenarios, be advised that read-only collections are still not thread-safe.
From the ReadOnlyCollection<T>
documentation:
... if changes are made to the underlying collection, the read-only collection reflects those changes
Since collections, like List<T>
and others, are not thread safe, so is not the read-only collection.
Important: There are some corner cases which you won't find explicitly explained in MSDN. Some of the operations that seemingly only read content of a collection, are in fact modifying the internal structures of the collection. Why is this not specified? - One obvious reason is because that is an implementation detail which doesn't reflect on the API. The result is that even if you don't modify the List<T>
wrapped into an ReadOnlyCollection<T>
, and only use getters, the crash could still happen in multi-threaded environment!
Bottom line is that common collections, even when wrapped into a ReadOnlyCollection
cannot be used in multi-threaded environment out of the box.
As opposed to ReadOnlyCollection
, immutable collections do guarantee that none of the internal structures will ever change after a reference to a collection has been obtained. Note that these structures are still not truly immutable. They are, instead, freezable. That means that the structure will internally change for a while until it is frozen and returned to the caller. Beyond that point, all other calls on the immutable collection will only make modifications outside the structures accessible through the original reference.
Conclusion: Read-only collections are not thread-safe; immutable collections are thread-safe.