我在并发集合和线程处理方面遇到了困难,特别是在ConcurrentDictionary中使用ConcurrentDictionary方法……我不能把它投入使用。我找不到任何好的例子.而且也不能完全理解,ConcurrentQueue在MSDN编程指南中的例子..
AddOrUpdate方法在ConcurrentDictionary中基本.我不能把它投入使用。我找不到任何好的例子.而且也不能完全理解,ConcurrentQueue在MSDN编程指南中的例子..
发布于 2011-01-03 13:48:22
在普通字典中,您可能会看到这样的代码:
Dictionary<string, int> dictionary = GetDictionary();
if (dictionary.ContainsKey("MyKey"))
{
dictionary["MyKey"] += 5;
}
else
{
dictionary.Add("MyKey", 5);
}这不是线程安全代码。有多个竞争条件:"MyKey“可以在调用ContainsKey之后添加/删除,与"MyKey”关联的值(如果有的话)可以在行中使用+=操作符在读取和赋值之间进行更改。
AddOrUpdate方法旨在解决这些线程问题,方法是提供一种机制来添加或更新与给定键关联的值,具体取决于密钥是否存在。它类似于TryGetValue,因为它将多个操作(在本例中,检查一个键,或者根据所述键的存在插入或修改一个值)组合到一个不受竞争条件影响的有效原子操作中。
为了使其具体化,下面是如何使用AddOrUpdate修复上面的代码
ConcurrentDictionary<string, int> dictionary = GetDictionary();
// Either insert the key "MyKey" with the value 5 or,
// if "MyKey" is already present, increase its value by 5.
dictionary.AddOrUpdate("MyKey", 5, (s, i) => i + 5);https://stackoverflow.com/questions/4584139
复制相似问题