看这么几句解释(英文原帖):

private static void ConcurrentDictionary()
{
var dict = new ConcurrentDictionary<int, string>();
ThreadPool.QueueUserWorkItem(LongGetOrAdd(dict, ));
ThreadPool.QueueUserWorkItem(LongGetOrAdd(dict, ));
} private static WaitCallback LongGetOrAdd(ConcurrentDictionary<int, string> dict, int index)
{
return o => dict.GetOrAdd(index,i =>
{
Console.WriteLine("Adding!");
Thread.SpinWait(); return i.ToString();
}
);
}

1) threadA calls GetOrAdd, finds no item and creates a new item to Add by invoking the valueFactory delegate.

线程A调用GetOrAdd,发现数据不存在并创建了一条新数据,准备调用委托方法添加数据

2) threadB calls GetOrAdd concurrently, its valueFactory delegate is invoked and it arrives at the internal lock before threadA, and so its new key-value pair is added to the dictionary.

线程B现在也在调用GetOrAdd方法,它的委托被调用了,比线程A先进入GetOrAdd内部的锁,因此它创建的键值对被添加到dict中了

3) threadA’s user delegate completes, and the thread arrives at the lock, but now sees that the item exists already

线A的委托执行完成了,并且也获得了GetOrAdd的锁,但是现在发现相关数据已经存在了

4) threadA performs a "Get", and returns the data th at was previously added by threadB.

线程A执行“Get”,返回之前被线程B添加的数据

不止这个英文原帖,好多国内的帖子都在说这个问题。

然而我觉得这并不是个问题,这最多是一个编程时需要注意的事项,微软的这个设计是合理的:ConcurrentDictionary没有理由也没有职责去把外部代码加锁,外部代码的同步应该由

外部控制。回头看看上面的解释,我们发现只不过是传递给ConcurrentDictionary的委托被执行了不止一次,但数据仍然只添加了一次,ConcurrentDictionary已经完全履行了自己的职责,而且MSDN也作了相关的说明(事实上,上面的四句英文也来自MSDN):

The user delegate that is passed to these methods is invoked outside of the dictionary's internal lock. (This is done to prevent unknown code from blocking all threads.)

传递进来的用户委托在字典内部锁的外面调用,这么做是为了防止阻塞所有相关线程,具体参考MSDN

都说ConcurrentDictionary<TKey, TValue>有陷阱的更多相关文章

  1. 线程安全集合 ConcurrentDictionary<TKey, TValue> 类

    ConcurrentDictionary<TKey, TValue> 类 [表示可由多个线程同时访问的键/值对的线程安全集合.] 支持 .NET Framework 4.0 及以上. 示例 ...

  2. C#字典 Dictionary<Tkey,Tvalue> 之线程安全问题 ConcurrentDictionary<Tkey,Tvalue> 多线程字典

    ConcurrentDictionary<Tkey,Tvalue>  Model #region 程序集 mscorlib, Version=4.0.0.0, Culture=neutra ...

  3. .net源码分析 - ConcurrentDictionary<TKey, TValue>

    List源码分析 Dictionary源码分析 ConcurrentDictionary源码分析 继上篇Dictionary源码分析,上篇讲过的在这里不会再重复 ConcurrentDictionar ...

  4. ConcurrentDictionary<TKey, TValue>的AddOrUpdate方法

    https://msdn.microsoft.com/zh-cn/library/ee378665(v=vs.110).aspx 此方法有一共有2个,现在只讨论其中一个 public TValue A ...

  5. c# 扩展方法奇思妙用基础篇五:Dictionary<TKey, TValue> 扩展

    Dictionary<TKey, TValue>类是常用的一个基础类,但用起来有时确不是很方便.本文逐一讨论,并使用扩展方法解决. 向字典中添加键和值 添加键和值使用 Add 方法,但很多 ...

  6. “线程安全的” Dictionary(TKey,TValue)

    这是一篇翻译,专门介绍Dictionary线程安全问题,原文网址如下 http://www.grumpydev.com/2010/02/25/thread-safe-dictionarytkeytva ...

  7. .net源码分析 – Dictionary<TKey, TValue>

    接上篇:.net源码分析 – List<T> Dictionary<TKey, TValue>源码地址:https://github.com/dotnet/corefx/blo ...

  8. .NET中Dictionary<TKey, TValue>浅析

    .NET中Dictionary<TKey, Tvalue>是非常常用的key-value的数据结构,也就是其实就是传说中的哈希表..NET中还有一个叫做Hashtable的类型,两个类型都 ...

  9. .net学习笔记----有序集合SortedList、SortedList<TKey,TValue>、SortedDictionary<TKey,TValue>

    无论是常用的List<T>.Hashtable还是ListDictionary<TKey,TValue>,在保存值的时候都是无序的,而今天要介绍的集合类SortedList和S ...

随机推荐

  1. Demo学习: CalendarPanel

    CalendarPane 学习CalendarPanel控件的常用事件. DayClick(...) //点击日期块空白部分触发EventClick(...) //点击日期块上事件触发RangeSel ...

  2. 【JPA】query新对象 需要 构造函数

    构造函数 @Query("select g from Note g where id=?1" ) Note findById(Long id); @Query("sele ...

  3. 开发设计模式(八)抽象工厂模式(Abstract Factory Pattern)

    抽象工厂模式主要有以下角色: 抽象工厂角色:担任这个角色的是工厂方法模式的核心,它是与应用系统的商业逻辑无关的.通常使用接口或抽象类实现.    具体工厂角色:这个角色直接在客户端的调用下创建产品的实 ...

  4. 重置mysql密码

    如何修改mysql root密码 忘记MySQL ROOT密码是在MySQ使用中很常见的问题,可是有很多朋友并不会重置ROOT密码,那叫苦啊,特写此文章与大家交流: 1.编辑MySQL的配置文件:my ...

  5. import information website

    1. 一个很好的展示如何review paper和response to reviewer的网站:openview 该网站给出了许多paper review的例子(如何你是reviewer,那么可以参 ...

  6. C# xml2json

    using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.We ...

  7. PHP 系统常量及自定义常量

    __FILE__ 这个默认常量是 PHP 程序文件名.若引用文件 (include 或 require)则在引用文件内的该常量为引用文件名,而不是引用它的文件名. __LINE__ 这个默认常量是 P ...

  8. lr11 BUG?Failed to send data by channels - post message failed.

    问题描述   : http协议,场景运行一会之后,报错! erro信息: Failed to send data by channels - post message failed. 解决方法 :ht ...

  9. [codility]Grocery-store

    http://codility.com/demo/take-sample-test/hydrogenium2013 用Dijkstra求最短路径,同时和D[i]比较判断是不是能到.用了优先队列优化,复 ...

  10. VCL+FMX 双剑合壁编程

    VCL 是经典,FMX 是新生,新生事物总会带来一些好玩新奇的东西.舍弃经典是浪费,不了解新生事物是等死,那么我们来一个二合一双剑合壁又如何呢? 要双剑合壁,就得投些机,取些巧.由于 Delphi / ...