c# - 为什么我需要从 ConcurrentDictionary 转换为 Dictionary 才能使用 Add()?

标签 c# concurrency concurrentdictionary

如果我有一个 ConcurrentDictionary 并且想使用 Add() 函数,我需要转换为 IDictionary:

var cd = new ConcurrentDictionary<int, int>();
cd.Add(1, 1);  // Compile error: does not contain a definition for 'Add'
IDictionary<int, int> id = cd;
id.Add(1, 1);  // Works

问题 ConcurrentDictionary and IDictionary告诉我这是因为 ConcurrentDictionary 使用私有(private)方法显式实现了 IDictionary

我的问题:为什么 ConcurrentDictionary 是这样实现的?隐藏已实现接口(interface)的使用有什么好处?

最佳答案

My question: Why is ConcurrentDictionary implemented like that?

我相信这是为了鼓励您考虑并发的含义 - 多个线程可能同时写入相同的 key 。因此,添加现有 key 不太可能是编程错误,应谨慎考虑。

  • 如果要无条件覆盖,使用索引器
  • 如果要添加或更新,其中更新可以使用现有值,使用AddOrUpdate
  • 如果您希望尽可能添加,但不覆盖任何现有值,请使用 TryAdd

如果您发现自己经常需要现有的 Add 行为,您总是可以编写自己的扩展方法。

关于c# - 为什么我需要从 ConcurrentDictionary 转换为 Dictionary 才能使用 Add()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21847703/

相关文章:

C# 数据库应用并发

c# - 关于使用 ConcurrentDictionary 的一些问题

concurrentdictionary - 如何选择并发字典的并发级别

c# - 向 MediatR 行为管道添加验证?

c# - EF6 - 在应用程序配置文件中找不到名为 'Data Source=...' 的连接字符串

c# - 什么能比并发集合更好地解决这种多线程场景

c++ - VS2010 C++ 并发运行时 - 如何强制单线程模式?

c# - 我如何告诉 `ConcurrentDictionary.GetOrAdd` 不添加值?

c# - 优先级、结合性和顺序之间有什么区别?

c# - 使用 MIP SDK 从 MS 365 个人帐户解密加密的 Office 365 电子邮件