2

我有以下字典并希望使其不可变;

var dict = ConcurrentDictionary<Type, ConcurrentDictionary<Type, Action>>

然后我打电话

var immmutableDict = dict.ToImmutableDictionary();

然而,这仍然会给ConcurrentDictionary<Type, Action>我相信的内部字典。

如何使用现有函数以线程安全的方式制作整个字典的不可变副本,或者我是否需要锁定整个操作以确保原子转换?

ImmutableDictionary<Type, ImmutableDictionary<Type, Action>>

或者,如果上述方法不可行,我可以重构代码以从一开始就使用 ReadOnlyDictionary 字典,但是我面临与内部字典相同的挑战,以使其在构造过程中只读:

var dict2 = new Dictionary<Type, Dictionary<Type, InstanceProducer>>();
/* snip perform adds to above dictionary to initialise state */

var immutableDict = dict2.ReadOnlyDictionary(); // ????
// where ReadOnlyDictionary<Type, ReadOnlyDictionary<Type, InstanceProducer>>(); is returned
// i need to make the above immutable with an immutable internal dictionary
4

2 回答 2

2

您只需要将每个内部字典也转换为不可变字典,然后从中创建一个新的 ImmutableDictionary。

ImmutableDictionary<Type, ImmutableDictionary<Type, Action>> immutableDict = dict
    .ToImmutableDictionary(e => e.Key, e => e.Value.ToImmutableDictionary());
于 2020-08-18T16:53:31.877 回答
1

但是,我相信这仍然会给内部 ConcurrentDictionary<Type, Action> 字典。

来电:

var immmutableDict = dict.ToImmutableDictionary();

将创建一个 type: 的结果ImutableDictionary<Type, ConcurrentDictionary<Type, Action>,所以它不会是ConcurrentDictionary.

如何使用现有函数以线程安全的方式制作整个字典的不可变副本,或者我是否需要锁定整个操作以确保原子转换?

要了解其dict.ToImmutableDictionary()工作原理,请阅读官方文档,其中说:

枚举一系列键/值对并生成其内容的不可变字典。

这个线程安全吗?是的,因为ImmutableDictionary它是线程安全的,并且从中创建一个ConcurrentDictionary也应该是线程安全的。

但是,值得问自己另一个问题:

  • 为什么我需要这个?

这个问题的原因是Immutable这个词,这意味着每次修改发生时它都会创建一个新的数据实例。

考虑到多线程意味着多线程访问可能会更改数据(除非您知道它不会被更改),它可能会对性能造成很大的影响。

于 2020-08-18T16:47:38.523 回答