编写以下代码是否安全? private static readonly IReadOnlyDictionarystring, string Map = new Dictionarystring, string{ ["A"] = "AAA", ["B"] = "BBB", ["C"] = "CCC"}; 我知道ConcurrencyDictionary是实现字典线程安全的标准方
private static readonly IReadOnlyDictionary<string, string> Map = new Dictionary<string, string> { ["A"] = "AAA", ["B"] = "BBB", ["C"] = "CCC" };
我知道ConcurrencyDictionary是实现字典线程安全的标准方法.但是,由于我需要的是一个“常量”映射,我从不打算修改它,初始化一个只读的IReadOnlyDictionary静态字段是否100%安全?
对于线程安全而言重要的是对象的实际类型(Dictionary),而不是变量的类型(IReadOnlyDictionary).根据documentation:
A
Dictionary<TKey, TValue>
can support multiple readers concurrently, as long as the collection is not modified.
因此,您的代码很好 – 当然,假设没有人将您的变量转换回Dictionary并修改它.如果您担心这种可能性,请将您的词典包装在ReadOnlyDictionary中.