简体   繁体   English

是否需要保护对.net集合的只读并发访问?

[英]Does read-only concurrent access to .net collections need to be guarded?

拥有一个可能会看到非常高的并发只读访问权限的.net集合(字典),它是否仍然需要保护,这意味着我应该使用该集合的线程安全版本或使用同步机制或线程安全a仅存在并发读写活动的主题?

Access to a collection needs to be synchronized only when reads occur concurrently with writes. 只有当读取与写入同时发生时,才需要同步对集合的访问。

If your collection is constructed once at the beginning of the program, and then accessed only for reading its elements or iterating over its content, then there is no need to add any additional synchronization around the reads. 如果您的集合在程序开始时构造一次,然后仅在读取其元素或迭代其内容时被访问,则无需在读取周围添加任何其他同步。

.NET framework offers an Immutable Collections package to ensure this flow of execution. .NET框架提供了一个Immutable Collections包来确保这个执行流程。 You build your immutable collection upfront, and then your code has no way to modify it even inadvertently. 您预先构建了不可变集合,然后您的代码无法在无意中修改它。

Use ConcurrentDictionary which is a thread-safe collection of key/value pairs that and allows to be accessed by multiple threads concurrently. 使用ConcurrentDictionary ,它是一个线程安全的键/值对集合,允许多个线程同时访问。 You can read at ConcurrentDictionary . 您可以在ConcurrentDictionary上阅读。

ConcurrentDictionary<TKey, TValue> implements the IReadOnlyCollection<T> and IReadOnlyDictionary<TKey, TValue> interfaces starting with the .NET Framework 4.6; ConcurrentDictionary<TKey, TValue>实现从.NET Framework 4.6开始的IReadOnlyCollection<T>IReadOnlyDictionary<TKey, TValue>接口; in previous versions of the .NET Framework, the ConcurrentDictionary class did not implement these interfaces. 在以前版本的.NET Framework中,ConcurrentDictionary类没有实现这些接口。

All the operations of this class are atomic and are thread-safe The only exceptions are the methods that accept a delegate, that is, AddOrUpdate and GetOrAdd. 此类的所有操作都是原子的并且是线程安全的唯一例外是接受委托的方法,即AddOrUpdate和GetOrAdd。

For modifications and write operations to the dictionary, ConcurrentDictionary<TKey, TValue> uses fine-grained locking to ensure thread safety. 对于字典的修改和写入操作, ConcurrentDictionary<TKey, TValue>使用细粒度锁定来确保线程安全。

Read operations on the dictionary are performed in a lock-free manner . 字典上的读取操作以无锁方式执行

However, delegates for these methods are called outside the locks to avoid the problems that can arise from executing unknown code under a lock. 但是,这些方法的委托在锁外部调用,以避免在锁定下执行未知代码时可能出现的问题。 Therefore, the code executed by these delegates is not subject to the atomicity of the operation. 因此,这些代理执行的代码不受操作的原子性影响。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM