多级ConcurrentDictionary还是线程安全的吗?
我有这样定义的四级数据结构:
Dictionary<Type1, Dictionary<Type2, Dictionary<Type3, List<Type4>>>>
整个事物被封装在一个类中,该类也保持线程安全。目前,它只是在读取/操作数据时锁定整个集合(读取比写入更常见几个数量级)。
我正在考虑用 ConcurrentDictionary 替换
和 Dictionary
List
以及 < code>ConcurrentBag(其项目不必订购)。
如果这样做,我可以消除锁并确保并发集合能够正确完成其工作吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我迟了将近一年才提出这个问题..但以防万一有人发现自己处于与 Matěj Zábský 类似的位置,问问自己:
你可以使用
Dictionary, List
Dictionary, List
Dictionary, List<输入4>>
代替?使用起来要容易得多,并且考虑到哈希表(即字典)是 O(1) 数据结构,具有相当大的常量组件(如果您转向 ConcurrentDictionary 则更是如此),它可能会执行速度也更快。它还会使用更少的内存,并且转换为 ConcurrentDictionary 也非常简单。
当然,如果您需要枚举给定
Type1
键的所有给定Type2
,则嵌套字典可能是最佳选择。但这是一个要求吗?I'm nearly a year late to the question.. but just in case anyone finds themselves in a similar position to Matěj Zábský, ask yourself:
Can you use a
Dictionary<Tuple<Type1, Type2, Type3>, List<Type4>>
instead?Considerably easier to work with, and considering that hash tables (ie Dictionaries) are O(1) data structures with a somewhat hefty constant component (even more so if you move to a
ConcurrentDictionary
) it'd likely perform faster too. It'd also use less memory, and be pretty trivial to convert to aConcurrentDictionary
.Of course if you need to enumerate all of a given
Type2
for a givenType1
key, the nested dictionaries is possibly the way to go. But is that a requirement?并发集合将防止数据损坏和崩溃,但代码在语义上不会与当前代码等效。例如,如果您迭代并发词典之一,某些项目可能属于不同的更新:
如果您想保持现在的确切行为,同时节省锁定成本,您可能需要使用 ReaderWriterLockSlim 特别适合读取多于写入的情况。
The concurrent collections will prevent data corruption and crashes, but the code won't be semantically equivalent to your current one. For example, if you iterate one of the concurrent dictionaries, some of the items may belong to different updates:
If you want to maintain the exact behavior you have now, yet save on the cost of locking, you may want to lock with ReaderWriterLockSlim which is especially suited for cases with more reads than writes.