gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 21:08:50 26 4
gpt4 key购买 nike

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

我假设我可以在 ConcurrentDictionary 上做任何我喜欢的操作本身,但是如果我创建一个 System.Collections.Generic.List<T> 会怎样?的 Dictionary<int, int>来自那个ConcurrentDictionary并修改它?

虽然我假设一旦 ToList,我在“一行”中使用 LINQ 创建了列表被执行我脱离了安全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>>

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

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

当然不是线程安全的

关于c# - 多线程访问 System.Collection.Concurrent 中的非线程安全值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39171726/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com