Koda
Koda

Reputation: 1857

Threadsafety dictionary C#

A colleague of mine recently stated it is fine for multiple read write threads to access a c# dictionary if you don't mind retreiving stale data. His justification was that since the program would reapeatedly read from the dictionary, stale data won't be an issue.

I told him that locking a collection was always necessary when you have a writer thread because the internal state of the collection will get corrupted.

Am I mistaken?

Upvotes: 3

Views: 1305

Answers (3)

penartur
penartur

Reputation: 9912

From http://msdn.microsoft.com/en-us/library/xfhwa508.aspx :

A Dictionary can support multiple readers concurrently, as long as the collection is not modified. Even so, enumerating through a collection is intrinsically not a thread-safe procedure. In the rare case where an enumeration contends with write accesses, the collection must be locked during the entire enumeration. To allow the collection to be accessed by multiple threads for reading and writing, you must implement your own synchronization.

For a thread-safe alternative, see ConcurrentDictionary<TKey, TValue>.

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

You are correct, and your colleague is wrong: one can access a dictionary from multiple threads only in the absence of writers.

.NET 4.0 adds ConcurrentDictionary<K,T> class that does precisely what its name implies.

Upvotes: 8

Adam Robinson
Adam Robinson

Reputation: 185593

You are correct in that some form of locking is required for writing, though just having a write doesn't mean that you have to lock() { } every access to the collection.

As you say, the non-synchronized versions of the built-in collections are thread safe only for reading. Typically a ReadWriterLockSlim is used to manage concurrent access in cases where writes can happen, as it will allow for multiple threads to access the collection as long as no writes are taking place, but only one thread (the writer) during a write.

Upvotes: 1

Related Questions