多线程访问 System.Collection.Concurrent 中的非线程安全值?

Multithreaded access to non-threadsafe values within a System.Collection.Concurrent?

如果我使用来自 System.Collection.Concurrent 命名空间的集合,例如 ConcurrentDictionary<K, V>,其键 and/or 值类型不是线程安全的,例如 ConcurrentDictionary<int, Dictionary<int, int>> 可能面临哪些问题?

我假设我可以对 ConcurrentDictionary 本身执行任何我喜欢的操作,但是如果我从 ConcurrentDictionary 创建 Dictionary<int, int>System.Collections.Generic.List<T> 会怎么样并修改它?

这里我在 "one line" 中使用 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 is by itself self for access from multiple threads (TryAdd, TryGetValue,等等...)。

重要的是要了解 ConcurrentDictionary 包含的对象不是线程安全的,而是 ConcurrentDictionary 本身。


如果您从多个线程访问字典中包含的特定值,那么您还必须确保它是线程安全的。

因为结果来自:

conDict.Select(x => x.Value)

是:

IEnumerable<Dictionary<int, int>>

并且它不再与 ConcurrentDictionary 有任何关系 - List<Dictionary<int, int>> 检索到:

conDict.Select(x => x.Value).ToList()

当然是不是线程安全的