Tuesday, April 13, 2010

Hashtable thread safety

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.

Synchronized supports multiple writing threads, provided that no threads are reading the Hashtable.
The synchronized wrapper does not provide thread-safe access in the case of one or more readers and one or more writers.

Hashtable myCollection = new Hashtable();
 
//... multiple thread usage via Hashtable.Synchronized(myCollection);
lock(myCollection.SyncRoot) {
  foreach (Object item in myCollection) {
  // ... here is reading operation
  }
}

0 коммент.:

Post a Comment

Powered by Blogger.