Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 233
Koda Avatar asked Jul 27 '26 10:07

Koda


2 Answers

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.

like image 137
Sergey Kalinichenko Avatar answered Jul 29 '26 01:07

Sergey Kalinichenko


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.

like image 39
Adam Robinson Avatar answered Jul 29 '26 03:07

Adam Robinson