Reputation: 1596
In terms of thread-safety, is there any difference between HashTable and Dictionary? I don't see any...According to msdn, both are defined as follows :-
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.
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.
Upvotes: 6
Views: 6721
Reputation: 6217
Both classes allows multiple readers at once without lock, both must be locked for multiple writers. The difference is, that Hashtable allows ONE writer together with multiple readers without locking, while this is not safe with Dictionary. So with Hashtable only writes must be locked. If both Keys and Values are reference-type (and so no boxing/unboxing is needed), Hashtable can be faster than Dictionary in scenarios with many readers and one (or more) writers, because readers don't have to wait for lock at all. With Dictionary the same scenario requires using ReaderWriterLock.
Upvotes: 15