多层ConcurrentDictionary仍然是线程安全的吗? [英] Is multi-level ConcurrentDictionary still thread-safe?

查看:200
本文介绍了多层ConcurrentDictionary仍然是线程安全的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样定义的四级数据结构:

I have four level data structure defined like this:

Dictionary<Type1, Dictionary<Type2, Dictionary<Type3, List<Type4>>>>

整个内容封装在一个也保持线程安全性的类中。目前,它只是在读取/处理数据时锁定整个集合(读取比写入更常见几个数量级)。

The whole thing is encapsulated in a class which also maintains thread-safety. Currently it just locks whole collection while it reads/manipulates the data (reading is by orders of magnitude more common than writing).

我正在考虑替换<$ c带有 ConcurrentDictionary的$ c> Dictionary List ConcurrentBag (不必订购其商品)。

I was thinking of replacing the Dictionary with ConcurrentDictionary and List with ConcurrentBag (its items don't have to be ordered).

如果这样做,是否可以消除锁定并确保并发集合可以正确执行其工作?

If I do so, can I just eliminate the locks and be sure the concurrent collections will do their job correctly?

推荐答案

并发收集可以防止数据损坏和崩溃,但是从语义上讲,该代码不会与您当前的代码等效。例如,如果您迭代其中一个并发词典,则某些项可能属于不同的更新

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:



字典返回的枚举数可以安全地与读操作同时使用
并写入
字典,但是
并不代表​​
字典的即时快照。通过枚举器公开的
内容可能包含在调用GetEnumerator之后对字典
进行的
修改。

The enumerator returned from the dictionary is safe to use concurrently with reads and writes to the dictionary, however it does not represent a moment-in-time snapshot of the dictionary. The contents exposed through the enumerator may contain modifications made to the dictionary after GetEnumerator was called.

如果您想保持现在的确切行为,但又节省了锁定成本,则可以使用 ReaderWriterLockSlim ,它特别适合于读取多于写入的情况。

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.

这篇关于多层ConcurrentDictionary仍然是线程安全的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆