在.NET Framework 中,有Dictionary
和ConcurrentDictionary
。
这些方法提供了Add
、Remove
等方法...
我知道当我们设计一个多线程程序时,我们使用ConcurrentDictionary
来代替Dictionary
来保证线程安全。
我想知道为什么 ConcurrentDictionary
有 AddOrUpdate
, GetOrAdd
和类似的方法,而 Dictionary
没有。
我们总是喜欢下面的代码从 Dictionary
中获取对象:
var dict = new Dictionary<string, object>();
object tmp;
if (dict.ContainsKey("key"))
{
tmp = dict["key"];
}
else
{
dict["key"] = new object();
tmp = new object();
}
但是使用ConcurrentDictionary
时,类似的代码只有一行而已。
var conDict = new ConcurrentDictionary<string, object>();
var tmp = conDict.GetOrAdd("key", new object());
我希望 .NET 有这些方法,但为什么没有?
最佳答案
因为这样的方法是:
在并发上下文中工作的最低限度。你不能拆分
Get
和Add
在没有锁定的两个独立步骤中,仍然会产生正确的结果。为
Dictionary<TKey, TValue>
实现时,它隐含地表示某种程度的线程安全,就好像Dictionary<TKey, TValue>
可以正确处理这件事。它不能,所以它只是没有实现。这不会阻止您制作扩展方法来做类似的事情。public static TValue GetOrAdd<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key, Func<TKey, TValue> valueGenerator) { // // WARNING: this method is not thread-safe and not intended as such. // if (!dict.TryGetValue(key, out TValue value)) { value = valueGenerator(key); dict.Add(key, value); } return value; }
关于c# - 为什么 ConcurrentDictionary 有 AddOrUpdate 和 GetOrAdd,而 Dictionary 没有?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57621418/