Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Dictionary and Hashtable in terms of thread-safety

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

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.

Dictionary

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.

like image 694
rajibdotnet Avatar asked Apr 21 '12 01:04

rajibdotnet


1 Answers

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.

like image 69
Ňuf Avatar answered Oct 25 '22 20:10

Ňuf