第6章:使用并发集合
6.1、简介
ConcurrentQueue:队列(Cas原子比较和交换)、ConcurrentStack:堆栈(Cas原子比较和交换)、ConcurrentBag:支持重复的无序集合
避免使用Count,复杂度O(N),IsEmpty属性是O(1)。
ConncurrentDictionary:字典,读不加锁,写加锁。避免使用Count、IsEmpty、keys、Values、CopyTo以及ToArray。
6.2、ConcurrentDictionary
写比Dictionary慢、读比Dictionary快,但是只有读取,也不建议用ConcurrentDictionary
const string Item = "Dictionary Item"; public static string CuttentItem; 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:{sw.Elapsed}"); sw.Restart(); for (int i = 0; i < 1000000; i++) { concurrentDictionary[i] = Item; } sw.Stop(); Console.WriteLine($"Writing to concurrent dictionary:{sw.Elapsed}"); sw.Restart(); for (int i = 0; i < 1000000; i++) { lock (dictionary) { CuttentItem = dictionary[i]; } } sw.Stop(); Console.WriteLine($"Reading from dictionary with a lock:{sw.Elapsed}"); sw.Restart(); for (int i = 0; i < 1000000; i++) { CuttentItem = concurrentDictionary[i]; } sw.Stop(); Console.WriteLine($"Reading from concurrent dictionary:{sw.Elapsed}"); Console.Read(); }
6.3、使用ConcurrentQueue实现异步处理

浙公网安备 33010602011771号