【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