c# HashTable线程安全吗?

c# Is HashTable thread safe?

如果我没理解错的话,默认情况下,HashTable 和 Dictionary 都不是线程安全的。

为了使 HashTable 线程安全,需要使用 Hashtable.Synchronized(Hashtable) 方法。

为了使 Dictionary 线程安全,需要使用 ConcurrentDictionary 或实现您自己的锁逻辑。

我的理解正确吗?

你是对的,HashTable 和 Dictionary 不是线程安全的。使用 HashTable.Synchronized 函数可以使哈希表(某种程度上)线程安全。这会在 HashTable 周围创建一个包装器,只允许一个写入者和多个读取者访问 HashTable。但是

HashTable 的包装器不是完全线程安全的,一个人可以迭代集合,而另一个线程仍然可以同时更改集合,从而导致异常。

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://docs.microsoft.com/en-us/dotnet/api/system.collections.hashtable.synchronized?view=netcore-3.1

根据情况,我会从 System.Collections.Concurrent 命名空间中选择一个集合。这是最好的描述:https://docs.microsoft.com/en-us/dotnet/standard/collections/thread-safe/

请记住,虽然这些系列不是最快的 - 如果速度很重要,我建议您根据您的特定需求定制一个。