Che*_*hta 7 .net c# .net-4.0 concurrent-collections
我在Concurrent集合和线程中遇到麻烦,特别是在ConcurrentDictionary中使用AddOrUpdate方法基本上.....我无法使用它...我找不到任何好的例子...而且还没有完全理解,在MSDN编程指南中ConcurrentQueue的例子..
ConcurrentDictionary中的AddOrUpdate方法基本上.....我无法使用它...我找不到任何好的例子...而且也无法完全理解,在MSDN编程指南中的ConcurrentQueue示例..
Dan*_*Tao 29
在常规字典中,您可能会看到如下代码:
Dictionary<string, int> dictionary = GetDictionary();
if (dictionary.ContainsKey("MyKey"))
{
dictionary["MyKey"] += 5;
}
else
{
dictionary.Add("MyKey", 5);
}
Run Code Online (Sandbox Code Playgroud)
这不是线程安全的代码.存在多种竞争条件:在调用之后可以添加/移除ContainsKey"MyKey",并且可以使用+=操作符在行中读取和分配之间改变与"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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13834 次 |
| 最近记录: |