.NET 4.5 has a new namespace System.Collections.Immutable
This package provides collections that are thread safe and guaranteed to never change their contents, also known as immutable collections.
I'm confused. Isn't the thread safety problem already solved by the ReadOnlyCollection class? Why use ImmutableList instead?
I know there's also an IReadOnlyList interface. That doesn't solve the thread safety problem implicitly, because other threads may edit the object by another interface.
When you don't expect to modify a collection, it's a good practice to defensively copy it into an immutable collection. Immutable lists have many advantages over their mutable siblings, like they are thread-safe, more memory-efficient, and can be passed to untrusted libraries without any side effects.
3 Answers. Show activity on this post. The fact that ReadOnlyCollection is immutable means that the collection cannot be modified, i.e. no objects can be added or removed from the collection. This does not mean that the objects it contains immutable.
Represents an immutable list, which is a strongly typed list of objects that can be accessed by index.
List<T> is not thread safe while ConcurrentBag is.
With a ReadOnlyCollection
:
A collection that is read-only is simply a collection with a wrapper that prevents modifying the collection; therefore, if changes are made to the underlying collection, the read-only collection reflects those changes.
This can't happen with an ImmutableList
.
ReadOnlyCollection<T>
doesn't solve any of the thread safety problems. It is merely a wrapper around Ilist<T>
. It doesn't exposes members to modify the collection, but you can always modify it with the underlying collection reference.
If the underlying collection is modified, it isn't safe to enumerate the ReadOnlyCollection<T>
. If you do, you'll get the same InvalidOperationException
with message "Collection was modified; enumeration operation may not execute...".
From ReadOnlyCollection<T>
A ReadOnlyCollection can support multiple readers concurrently, as long as the collection is not modified. Even so, enumerating through a collection is intrinsically not a thread-safe procedure. To guarantee thread safety during enumeration, you can lock the collection during the entire enumeration. To allow the collection to be accessed by multiple threads for reading and writing, you must implement your own synchronization.
ImmutableList
on the other hand is immutable and thus inherently thread safe.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With