Reputation: 3617
Having a .net collection (a dictionary) that will potentially see very high concurrent read-only access, does it still need to be guarded meaning that I should be using a thread safe version of the collection or use synchronization mechanisms or is thread safety a topic only in presence of concurrent read and write activities?
Upvotes: 4
Views: 1202
Reputation: 10839
Use ConcurrentDictionary
which is a thread-safe collection of key/value pairs that and allows to be accessed by multiple threads concurrently. You can read at ConcurrentDictionary.
ConcurrentDictionary<TKey, TValue>
implements the IReadOnlyCollection<T>
and IReadOnlyDictionary<TKey, TValue>
interfaces starting with the .NET Framework 4.6; in previous versions of the .NET Framework, the ConcurrentDictionary class did not implement these interfaces.
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.
For modifications and write operations to the dictionary, ConcurrentDictionary<TKey, TValue>
uses fine-grained locking to ensure thread safety.
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.
Upvotes: 0
Reputation: 726479
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. You build your immutable collection upfront, and then your code has no way to modify it even inadvertently.
Upvotes: 5