Hashtable indicates a set of Key/Value pairs. These Key/Value pairs are organized based on the hash code of the Key. The Key cannot be null, and the Value can be null, this is different from Hashmap (it is not thread-safe). For Hashtable, it implements the IDictionary and ICollection interfaces. Its key and value are of the object type and do not support generics, to convert data types into boxing and unboxing, this will certainly have some impact on the performance. Therefore, Microsoft provides a set of key-value pairs that support generics, the Dictionary itself is not thread-safe. We need to lock it to avoid some errors in the multi-threaded environment.
Next let's take a look at the thread-safe Hashtable code snippet:
Hashtable ht = Hashtable.Synchronized(, ]);
Let's take a look at the Dictionary object, which can make the Attributes provided by its base class to implement thread security of its internal objects.
Dictionary<, > dic = Dictionary<, > ((dic ,
The following is an example of Dictionary thread security. We have two threads, t1 and t2. When we lock it, T1.
Dictionary<, > dic = Dictionary<, >= Thread(() => ((dic ICollection).SyncRoot) , );= Thread(() => ((dic ] = ;);
For Hashtable, if you want to lock it by writing and reading, you can also implement it by locking it in the code segment.
Thread t1 = Thread(() =>
OK. Let's talk about the thread security of hashtable. Finally, let's talk about the knowledge of thread security, because the program you wrote must be
In a multi-threaded environment.