相关疑难解决方法(0)

如何将字典转换为ConcurrentDictionary?

我已经看到如何将ConcurrentDictionary转换为Dictionary,但我有一个字典,并希望转换为ConcurrentDictionary.我该怎么做?...更好的是,我可以将link语句设置为ConcurrentDictionary吗?

var customers = _customerRepo.Query().Select().ToDictionary(x => x.id, x => x);
Run Code Online (Sandbox Code Playgroud)

.net c# asp.net dictionary concurrentdictionary

9
推荐指数
2
解决办法
9907
查看次数

根据类的当前实现,通过直接枚举 ConcurrentDictionary 将 ConcurrentDictionary 复制到普通 Dictionary 是否安全?

TL;DR: a 的单个枚举是否可以ConcurrentDictionary两次发出相同的键?该类的当前实现(.NET 5)是否ConcurrentDictionary允许这种可能性?


我有一个ConcurrentDictionary<string, decimal>由多个线程同时变异的 ,我想定期将其复制到普通Dictionary<string, decimal>,并将其传递到表示层以更新 UI 。有两种复制它的方法,带快照语义和不带快照语义:

var concurrent = new ConcurrentDictionary<string, decimal>();

var copy1 = new Dictionary<string, decimal>(concurrent.ToArray()); // Snapshot

var copy2 = new Dictionary<string, decimal>(concurrent); // On-the-go
Run Code Online (Sandbox Code Playgroud)

我非常确定第一种方法是安全的,因为该ToArray方法返回以下内容的一致视图ConcurrentDictionary

返回一个新数组,其中包含从 复制的键和值对的快照ConcurrentDictionary<TKey,TValue>

但我更喜欢使用第二种方法,因为它产生的争用较少。我担心获得的可能性ArgumentException: An item with the same key has already been added.文档似乎并没有排除这种可能性:

从字典返回的枚举器...并不代表字典的即时快照。通过枚举器暴露的内容可能包含GetEnumerator调用后对字典所做的修改。

这是让我担心的情况:

  1. 线程 A 开始枚举ConcurrentDictionary,并且键X由枚举器发出。然后该线程被操作系统暂时挂起。
  2. 线程 B 移除钥匙 …

c# multithreading dictionary concurrentdictionary

5
推荐指数
1
解决办法
1999
查看次数