gpt4 book ai didi

.net - Dictionary 和 Hashtable 在线程安全方面的区别

转载 作者:行者123 更新时间:2023-12-02 11:01:26 24 4
gpt4 key购买 nike

在线程安全方面,HashTable和Dictionary有什么区别吗?我没有看到任何...根据msdn,两者的定义如下:-

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.

最佳答案

这两个类都允许同时多个读取器而无需锁定,对于多个写入器都必须锁定。不同之处在于,Hashtable 允许一个 writer 与多个 reader 一起使用而无需锁定,而这对于 Dictionary 来说并不安全。因此,对于 Hashtable,只有写入操作必须被锁定。如果键和值都是引用类型(因此不需要装箱/拆箱),则在具有许多读者和一个(或多个)作者的情况下,哈希表可以比字典更快,因为读者不必等待锁定全部。对于字典,相同的场景需要使用 ReaderWriterLock .

关于.net - Dictionary 和 Hashtable 在线程安全方面的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10255456/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com