对System.Collection.Current中的非线程安全值的多线程访问
本文关键字:安全 多线程 访问 线程 Collection Current System | 更新日期: 2023-09-27 18:04:06
如果我使用的是来自System.Collection.Concurrent
命名空间的集合,例如ConcurrentDictionary<K, V>
,其键和/或值类型不是线程安全的,例如ConcurrentDictionary<int, Dictionary<int, int>>
可能会遇到什么问题
我假设我可以对ConcurrentDictionary
本身执行任何我喜欢的操作,但如果我从该ConcurrentDictionary
创建Dictionary<int, int>
的System.Collections.Generic.List<T>
并修改它呢?
在这里,我在"一行"中使用LINQ创建列表,尽管我假设一旦执行ToList
,我就脱离了ConcurrentDictionary
lock
的安全范围?
ConcurrentDictionary<int, Dictionary<int, int>> conDict = ...;
conDict.Select(x => x.Value).ToList().ForEach(x => x.Add(1, 2));
如果这是安全的或不安全的,我认为这太了
ConcurrentDictionary<int, Dictionary<int, int>> conDict = ...;
var regDictList = conDict.Select(x => x.Value).ToList();
regDictList.ForEach(x => x.Add(1, 2));
好吧,ConcurrentDictionary
本身可以从多个线程(TryAdd
、TryGetValue
等(进行访问。
重要的是要理解,线程安全的不是ConcurrentDictionary
所包含的对象,而是ConcurrentDictionary
本身。
如果您从多个线程访问字典中包含的特定值,则必须确保它也是线程安全的。
由于结果来自:
conDict.Select(x => x.Value)
是:
IEnumerable<Dictionary<int, int>>
它不再与CCD_ 16有任何关系——一个由检索的CCD_
conDict.Select(x => x.Value).ToList()
当然是线程不安全的