【C#】54. .Net中的并发集合——ConcurrentDictionary
来源:互联网 发布:oracle java api 编辑:程序博客网 时间:2024/06/08 00:04
转载自《C#多线程编程实例》
对于并行计算,我们需要使用适当的数据结构。这些结构具备可伸缩性,尽可能地避免锁,并且还能提供线程安全的访问。.Net Framework 引入了System.Collections.Concurrent 命名空间,包含了一些数据结构。
const string Item = "Dictionary item";public static string CurrentItem;
static void Main(string[] args){var concurrentDictionary = new ConcurrentDictionary<int, string>();var dictionary = new Dictionary<int, string>();var sw = new Stopwatch();sw.Start();for (int i = 0; i < 1000000; i++){lock (dictionary){dictionary[i] = Item;}}sw.Stop();Console.WriteLine("Writing to dictionary with a lock: {0}", sw.Elapsed);sw.Restart();for (int i = 0; i < 1000000; i++){concurrentDictionary[i] = Item;}sw.Stop();Console.WriteLine("Writing to a concurrent dictionary: {0}", sw.Elapsed);sw.Restart();for (int i = 0; i < 1000000; i++){lock (dictionary){CurrentItem = dictionary[i];}}sw.Stop();Console.WriteLine("Reading from dictionary with a lock: {0}", sw.Elapsed);sw.Restart();for (int i = 0; i < 1000000; i++){CurrentItem = concurrentDictionary[i];}sw.Stop();Console.WriteLine("Reading from a concurrent dictionary: {0}", sw.Elapsed);Console.Read();}
可以明显地看出使用lock配合Dictionary 与 ConcurrentDictionary 的性能差异:在“写”操作上,lock配合Dictionary显然快很多;而在“读”操作上,ConcurrentDictionary更快一些。但是请注意,这里使用的是单线程!如果线程数量上去,ConcurrentDictionary的效率会大大提升。
0 0
- 【C#】54. .Net中的并发集合——ConcurrentDictionary
- 【C#】55. .Net中的并发集合——ConcurrentQueue
- 【C#】56. .Net中的并发集合——ConcurrentStack
- 【C#】57. .Net中的并发集合——ConcurrentBag
- 【C#】58. .Net中的并发集合——BlockingCollection
- .NET的ConcurrentDictionary,线程安全集合类
- .Net多线程编程—并发集合
- JDK 中的并发集合
- 集合中的并发
- JAVA多线程—并发集合
- C#中字典集合HashTable、Dictionary、ConcurrentDictionary三者区别
- Java中的并发集合类
- .net 中的集合区别
- .Net中的集合类
- java并发系列——并发集合(一)
- java并发——多线程、线程池、并发集合
- Java7并发编程指南——第六章:并发集合
- C#OOP中的集合
- golang语言环境搭建
- 每天一个linux命令(14):head 命令
- 安卓蓝牙4.0和蓝牙多通道
- 文件对比工具中如何删除表格中的列表数据
- 如何让es6 写的 文件 import 起来
- 【C#】54. .Net中的并发集合——ConcurrentDictionary
- Trafodion表与HBase表的关系
- AES 之128位加密与解密
- Jmeter实现WebSocket协议的接口和性能测试方法
- Spring 整合 Redis
- 安卓TabLayout加小红点提示内容更新
- css3 2D--transform--scale缩放
- sql 中的 order by 多个列排序
- XCode 后台答应汉字不正常