文档章节

ConcurrentDictionary in dotnet

pczhangtl
 pczhangtl
发布于 2014/03/19 16:45
字数 681
阅读 69
收藏 0

行业解决方案、产品招募中!想赚钱就来传!>>>

ConcurrentDictionary<TKey,TValue> is a new type in the .NET Framework 4, living in the System.Collections.Concurrent namespace.  As noted in the MSDN documentation, ConcurrentDictionary “represents a thread-safe collection of key-value pairs that can be accessed by multiple threads concurrently.” 

While ConcurrentDictionary implements IDictionary<TKey, TValue> just as does Dictionary<TKey,TValue>, it also has several unique mechanisms for adding / updating key/value pairs in the dictionary, mechanisms specific to its concurrent focus.  Here is a summary of when to use which mechanism.

  • If you want to…
    • Add a new item to the dictionary only if the key doesn’t currently exist in the dictionary…
      • Use TryAdd.  TryAdd accepts the key and the value, and adds the pair to the dictionary if the key doesn’t currently exist in the dictionary.  The method returns whether or not the new pair was added.
        • public bool TryAdd(TKey key, TValue value)
    • Update the value for an existing key in the dictionary, but only if the existing value for that key is equal to a specific value…
      • Use TryUpdate.  TryUpdate accepts the key and the new value to set that key to, but it also accepts the value that the key in the dictionary must currently contain in order for the update to succeed.  You can think of TryUpdate like Interlocked.CompareExchange but for an element in the dictionary.
        • public bool TryUpdate(TKey key, TValue newValue, TValue comparisonValue)
    • Store a key/value pair into the dictionary unconditionally, overwriting any value for that key if the key already exists…
      • Use the indexer’s setter, e.g. dictionary[key] = newValue.
        • public TValue this[TKey key] { get; set; }
    • Add a key/value pair to the dictionary if the key doesn’t exist in the dictionary, or if the key does exist, update the value for the key based on the key’s existing value…
      • Use AddOrUpdate.  AddOrUpdate has two overloads:
        • One overload accepts the key as well as two delegates.  The first delegate is used if the key doesn’t exist in the dictionary; it accepts the key and returns the value that should be added for the key.  The second delegate is used if the key does exist: it accepts both the key and the current value for the key, and it returns the new value that should be set for the key.
          • public TValue AddOrUpdate(TKey key, Func<TKey, TValue> addValueFactory, Func<TKey, TValue, TValue> updateValueFactory)
        • The other overload accepts the key, an add value, and the update delegate.  This is exactly the same as the former overload, except that if the key isn’t in the dictionary, the provided value is added for the key, rather than invoking a delegate to get the necessary value
          • public TValue AddOrUpdate(TKey key, TValue addValue, Func<TKey, TValue, TValue> updateValueFactory)
    • Get the value for a key in the dictionary, adding the value to the dictionary (and returning it) if the key doesn’t exist…
      • Use GetOrAdd.  You can think of this as lazy-initialization for a key/value pair in the dictionary, getting the value if it’s there, or adding it and then getting it if it’s not.  As with AddOrUpdate, GetOrAdd provides two overloads: one takes the value to be added if the key doesn’t exist, and the other takes a delegate that will generate the value if the key doesn’t exist.
        • public TValue GetOrAdd(TKey key, TValue value)
        • public TValue GetOrAdd(TKey key, Func<TKey, TValue> valueFactory)

All of these operations are atomic and are thread-safe with regards to all other operations on the ConcurrentDictionary.  The only caveat to the atomicity of each operation is for those which accept a delegate, namely AddOrUpdate and GetOrAdd.  For modifications / writes to the dictionary, ConcurrentDictionary employs fine-grained locking to ensure thread-safety (reads on the dictionary are performed in a lock-free manner); however, these delegates are invoked outside of the locks in order to avoid the myriad of problems that can arise from executing unknown code under a lock.  As such, the code executed by these delegates is not subject to the atomicity of the operation.

pczhangtl
粉丝 46
博文 707
码字总数 113318
作品 0
浦东
高级程序员
私信 提问
加载中
请先登录后再评论。
高性能跨语言 RPC--Hprose

Hprose 是高性能远程对象服务引擎(High Performance Remote Object Service Engine)的缩写 —— 微服务首选引擎。 它是一个先进的轻量级的跨语言跨平台面向对象的高性能远程动态通讯中间件...

andot
2012/12/27
6.1W
28
.NET的ORM框架--SqlSmart

SqlSmart是一个DotNet类库,它可以充分利用 codeinsight ,面向对象技术来帮助程序员更快的,更准确到编写sql,这样的sql以容易重构的。 听起来陌生?这是想法我之前并没有在其他ORM技术,比如...

匿名
2010/03/04
8.2K
1
Ruby In Steel

Ruby In Steel是一个适用于Visual Studio2005的add-in。可以在VS2005里编写、运行Ruby程序。它的特点是非常类似c#等dotnet的编辑器,代码能折叠,能检查语法错误,支持Rails工程,中括号自动...

匿名
2008/10/07
1.7K
1
indeXus.Net Shared Cache

indeXus.Net SharedCache是高性能的、分布式的内存对象系统,用于在动态WEB或Win应用程序中减少数据库的负责,提高访问速度。SharedCache 全部的代码都是用c#写的,100% DotNet原生态。...

匿名
2008/11/10
3.3K
0
微信小程序版高性能跨语言平台--Hprose-wx

Hprose 是高性能远程对象服务引擎(High Performance Remote Object Service Engine)的缩写。本项目是 Hprose 2.0 的微信小程序专用版。 它是一个先进的轻量级的跨语言跨平台面向对象的高性...

andot
2016/11/11
3.1K
0

没有更多内容

加载失败,请刷新页面

加载更多

南宁银行卡

南宁银行卡 〖σ薇:391000268】确保全新一手货源,提供各大行。全新借记卡〖σ薇:391000268】确保全新一手货源,提供各大行。 今天立秋,本来是一个安静祥和的日子,但是特朗普签署的一道政令让...

科技之光
4分钟前
0
0
mac wasm 环境搭建 编译自己的fib

https://webassembly.org/ 安装cmake brew install cmake 没有brew https://brew.sh/index_zh-cn /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/i......

阿豪boy
5分钟前
0
0
Hacker News 简讯 2020-08-08

最后更新时间: 2020-08-08 00:01 To Head Off Regulators, Google Makes Certain Words Taboo - (themarkup.org) 为了阻止监管者,谷歌禁止使用某些词语 得分:106 | 评论:60 Facebook fired ......

FalconChen
10分钟前
23
1
vpp系列7-trace

前置 追踪包是必备的调试工具,可喜的是VPP中每个NODE都可以追踪包。且VPP提供了两种方式:普通trace 和 pcap trace, 且Wireshark最新版已经支持VPP pcap调度跟踪输出。 Trace 开始抓包 ...

messud4312
昨天
5
0
FastDFS的单机版安装

FastDFS的单机版安装 : 安装FastDFS文件系统,需要下载下面提供的几个安装包(这几个安装包也是上fastdfs官网下载的): fastdfs(主程序包): https://github.com/happyfish100/fastdfs...

猫狗熊
昨天
4
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部