为什么在 ReadOnlyCollection 上使用 ImmutableList?

NET 4.5有一个新的名称空间 系统,收集,不变

此包提供线程安全的集合,并保证不更改其内容,也称为不可变集合。

我很困惑。线程安全问题不是已经被 ReadOnlyCollection类解决了吗? 为什么还要用 不可变列表呢?


我知道还有一个 IReadOnlyList < em > interface 。这并不能隐式地解决线程安全问题,因为其他线程可能通过另一个接口编辑对象。

33686 次浏览

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, as the name suggests, can only be read.

On the other hand, you can append/remove items to/from an ImmutableList by calling its Add/Remove/Clear methods, for example, which return a new immutable list.

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.

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.

The main benefit is memory efficiency, not thread-safety.

The immutable collections in System.Collections.Immutable are designed in a way that allows modified versions of the collection to share data structures with un-modified copies of the same collection. The differences are encoded in clever ways that don't require duplication of the whole data structure. There is nice explanation of this at Immutable Collections.

ReadOnlyCollection requires a completely seperate copy of the collection to be created whenever a modification is made. This uses more memory and puts a higher load on the garbage collector.

As you've observed, both classes seek to guarantee that the collection can't have observable modifications. And both classes achieve that to some extent, assuming they aren't misused.

So far all technical aspects was told but no code. I created a small example shows main difference.

List<string> strings = new List<string>()
{
"Visual Studio 2017","Visual Studio 2019"
};
ReadOnlyCollection<string> readOnlyStrings = strings.AsReadOnly();
var immutableList = strings.ToImmutableList();
strings.Add("Visual Studio 2022");
Console.WriteLine("Readonly List");


foreach (string item in readOnlyStrings)
{
Console.WriteLine(item);
}
Console.WriteLine("Immutable List");


foreach (string item in immutableList)
{
Console.WriteLine(item);
}

Screenshot