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

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. IE6下input标签border问题

    IE6下input标签的border的样式border:none;是不起作用的!要设置border:0px;才行!

  2. Live帐号登陆win8系统不用输密码的方法

    win 8 系统旨在让大家日常的操作更加方便与快捷.因此,今天,小编将与大家分享的是如何利用Live帐号登陆win8系统,而不用输密码的方法.具体的步骤如下文所述. 按win+R打开运行输入cmd(在 ...

  3. oracle expdp 无法导出SYS下特定TABLE

    创建测试表: D:\app\product\\db_1>sqlplus "/as sysdba" SQL :: Copyright (c) , , Oracle. All r ...

  4. Python基于比较的排序

    排序是算法学习中最基本的问题. 1.平均时间复杂度均为O(N2)的排序 1.1 插入排序 插入排序对少量元素的排序非常有效.工作机制就像打牌一样,为了将牌插入到已排好序的牌中,需要将牌与手中的牌从右向 ...

  5. Python prettytable的使用方法

    Python prettytable的使用方法 prettytable可以整齐地输出一个表格信息: +-----------+------+------------+----------------- ...

  6. 简单3d RPG游戏 之 001 生命条(一)

    1.创建一个新项目,引用如下的包: 2.将asset里的First Person Controller拖入project作为游戏角色,将其命名为Player,将mainCamera删除,这样就是用Pl ...

  7. NUTCH Exception in thread "Thread-12751" java.lang.OutOfMemoryError: PermGen space

    转载自 :http://greemranqq.iteye.com/blog/1705867转载自:http://www.cnblogs.com/xwdreamer/archive/2011/11/21 ...

  8. Hyper-V中安装CentOS分辨率修改

    Hyper-V还是极好用的,不过对linux的支持优点问题, 比如默认情况,linux分辨率被锁定了,这里有一个比较简单的方法修改,针对CentOS grubby --update-kernel=AL ...

  9. CentOS搭建OpenVPN服务(简易版)

    OpenVPN服务端配置 1. 安装OpenVPN软件包 默认的Centos软件源里面没有OpenVPN的软件包,我们可以添加rpmforge的repo,从而实现yum安装openvpn 针对Cent ...

  10. Seven Python Tools All Data Scientists Should Know How to Use

    Seven Python Tools All Data Scientists Should Know How to Use If you’re an aspiring data scientist, ...