views:

985

answers:

5

Does anyone know of an implementation of a lock free hash table in C#? Or can anyone confirm for a fact that at least reads on a HashTable are thread-safe?

Edit:

I can read the documentation, but it's unclear.

"It is thread safe for multi-thread use when only one of the threads perform write (update) operations."

So, the question is, if I have multiple threads, and they all could write to the hashtable, I would use the writerlock. However, those same threads also read from the hashtable. Do I need a readerlock on the reads?

+4  A: 

Reads are thread-safe until the collection is modified.

Orion Adrian
A: 

You might want to use your hash table in conjunction with ReaderWriterLock because of what Orion said.

C. Ross
+3  A: 

From the documentation:

Hashtable is thread safe for use by multiple reader threads and a single writing thread. It is thread safe for multi-thread use when only one of the threads perform write (update) operations, which allows for lock-free reads provided that the writers are serialized to the Hashtable. To support multiple writers all operations on the Hashtable must be done through the wrapper returned by the Synchronized method, provided that there are no threads reading the Hashtable object.

Enumerating through a collection is intrinsically not a thread safe procedure. Even when a collection is synchronized, other threads can still modify the collection, which causes the enumerator to throw an exception. To guarantee thread safety during enumeration, you can either lock the collection during the entire enumeration or catch the exceptions resulting from changes made by other threads.

Kekoa
+1  A: 

You can write your own Lock free hashtable by creating a new one and swapping it every time you modify it - it works well if you don't modify it often. (because it's extremely cheap to read and very expensive to write).

Otherwise, I would recommend using a ReaderWriterLockSlim (assuming you read more than you write) or a Monitor (lock statement) if you write a lot.

Remi Lemarchand
+1  A: 

In addition .NET 4.0 is adding a ConcurrentDictionary to the System.Collections.Concurrent namespace...

Rick