【发布时间】:2020-08-18 16:25:04
【问题描述】:
我有以下字典并希望使其不可变;
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
【问题讨论】:
-
“线程安全时尚”和“原子转换”是什么意思?您的意思是希望生成的嵌套
ImmutableDictionary包含初始嵌套ConcurrentDictionary的快照吗?如果你想要快照语义,那么获取它们的唯一方法是调用方法ConcurrentDictionary.ToArray。ToImmutableDictionary扩展方法在IEnumerable接口上运行,因此它不会生成快照。生成的ImmutableDictionary可能包含在初始集合中从未共存的条目。
标签: c# .net concurrency immutable-collections