C# hashtable synchronized and SyncRoot(cost comparison)

Lionsure 2020-09-01 Original by the website

Multiple threads adding or deleting items in Hashtable at the same time may cause Hashtable errors, so it is essential to synchronize it. What are the synchronization methods?

 

1. Use Hashtable.Synchronized to synchronize

Hashtable ht = new Hashtable();
       ht = Hashtable.Synchronized(ht);

Or one step:

Hashtable ht = Hashtable.Synchronized(new Hashtable());

Tip: Using Hashtable.Synchronized is safer and more convenient, but the program overhead is also relatively large. Looking at the compiled ildasm code, we can see that this method actually adds synchronization code, but it is automatically implemented by .Net.

 

2. Use Hashtable.SyncRoot to synchronize

Hashtable ht = new Hashtable();
       lock(ht.SyncRoot)
       {
              ht.Add("UserName1", "2020-09-01 21:52:47");
              ht.Add("UserName2", "2020-09-01 21:53:21");
              ht.Add("UserName3", "2020-09-01 21:53:32");
       }

Tip: This method is to achieve synchronization by locking the Hashtable object, that is, when a thread is operating the Hashtable, other threads can only wait, and the previous thread has completed the operation, and the waiting thread can operate. Generally speaking, as long as the addition, modification and deletion of the Hashtable are locked, no errors will occur.

 

Two methods, as for which one to use, depends on your familiarity. If you are more familiar with synchronization-related knowledge or require higher efficiency in the program, then use the second method; if you have less knowledge about synchronization, the requirements for program efficiency are not very high, so use the first method, after all, it is convenient and fast.