-3

If I understand it correctly, HashTable and Dictionary are both not thread safe by default.

In order to make HashTable thread safe it is needed to use Hashtable.Synchronized(Hashtable) Method.

In order to make Dictionary thread safe it is needed to use ConcurrentDictionary or implement your own lock logic.

is my understanding correct?

Roesmi
  • 466
  • 5
  • 15
  • 2
    Who told you that HashTable is considered thread safe? If you found that in published documentation, please consider submitting a bug against it. – Eric Lippert Sep 29 '20 at 19:35
  • Related: [Concurrent HashSet in .NET Framework?](https://stackoverflow.com/q/18922985/18192) – Brian Sep 29 '20 at 19:48
  • _"why HashTable is considered thread safe"_ -- it's not, which makes your entire post a non-question. Please clarify what _problem_ you're trying to solve, and what _specifically_ you need help with. – Peter Duniho Sep 29 '20 at 20:24
  • @EricLippert in any search you do on google "hashtable vs dictionary c#" you can see it mentioned that hashtable is thread safe. – Roesmi Sep 29 '20 at 21:20
  • The [`Hashtable`](https://learn.microsoft.com/en-us/dotnet/api/system.collections.hashtable) class is obsolete. I had almost forgotten that it ever existed. It has been superseded by the `Dictionary` class. – Theodor Zoulias Oct 30 '20 at 15:50

1 Answers1

3

You are correct, HashTable and Dictionary are not thread safe. HashTable can be made (sort of) thread safe using the HashTable.Synchronized function. This creates a wrapper around the HashTable allowing only one writer and multiple readers to access HashTable. But.

The wrapper around the HashTable is not fully thread safe, one could iterate the collection while another thread could concurrently still change the collection resulting in an exception.

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.

-- https://learn.microsoft.com/en-us/dotnet/api/system.collections.hashtable.synchronized?view=netcore-3.1

Depending on the situation I would pick a collection from the System.Collections.Concurrent namespace. Which is best described here: https://learn.microsoft.com/en-us/dotnet/standard/collections/thread-safe/

Bear in mind though that these collections are not the fastest - if speed is important I would recommend tailoring one to your specific needs.

Thomas
  • 258
  • 2
  • 5