简体   繁体   English

字典的线程安全<TKey, TValue>

[英]Thread safety of a Dictionary<TKey, TValue>

If I initialize a generic dictionary once, and no further adds/updates/removes are allowed, is it safe to have multiple threads reading from it with no locking (assuming that the dictionary is initialized before the readers are started)?如果我初始化一个通用字典一次,并且不允许进一步添加/更新/删除,那么在没有锁定的情况下让多个线程从中读取是否安全(假设字典在读取器启动之前已初始化)?

There is a note in the help for the non-generic HashTable that says that it is safe for multiple readers, but I did not see something similar for the Generic Dictionary.非泛型 HashTable 的帮助中有一条注释说它对多个读者是安全的,但我没有看到 Generic Dictionary 类似的东西。

For your future reference, the documentation is here:供您将来参考,文档在此处:

http://msdn.microsoft.com/en-us/library/xfhwa508.aspx http://msdn.microsoft.com/en-us/library/xfhwa508.aspx

It says:它说:

A Dictionary can support multiple readers concurrently, as long as the collection is not modified.只要不修改集合,Dictionary 就可以同时支持多个阅读器。 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.要允许多个线程访问集合进行读写,您必须实现自己的同步。

Yes, it's safe if you don't modify the dictionary any more.是的,如果你不再修改字典是安全的。 Thread safety is only an issue in read/write scenarios线程安全只是读/写场景中的问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM