是一个只读的HashSet天生线程? [英] Is a read-only HashSet inherently threadsafe?
问题描述
如果我初始化的HashSet<>
在延迟
初始化,然后永远不变的内容,是的HashSet<>
固有线程安全的?是否有阅读需要锁定的操作?
If I initialize a HashSet<>
inside a Lazy
initializer and then never change the contents, is that HashSet<>
inherently threadsafe? Are there read actions that require locking?
类似的Java问题<一href="http://stackoverflow.com/questions/24263521/is-a-collection-threadsafe-if-its-only-written-in-the-constructor">here为收藏一般,基本上说是,但也有一些注意事项(即不要在此情况下适用)。
Similar Java question here for collections generally, which essentially says yes, but with some caveats (that don't apply in this situation).
推荐答案
是的,确实如此。只要的HashSet
对象的构造是线程安全的,访问它永远是线程安全的,只要内容没有改变。
Yes, it is. As long as the construction of the HashSet
object is thread safe, accessing it will always be thread safe as long as the contents doesn't change.
如果您初始化的懒
使用<一个href="http://msdn.microsoft.com/en-us/library/system.threading.lazythreadsafetymode(v=vs.110).aspx"><$c$c>LazyThreadSafetyMode.PublicationOnly$c$c>你可以肯定的延迟
的初始化是线程安全的。
If you initialize the Lazy
using LazyThreadSafetyMode.PublicationOnly
you can be sure the initialization of the Lazy
is thread safe.
当多个线程试图初始化延迟&LT; T&GT;同时
实例,所有线程都可以运行初始化方法(或默认的构造函数,如果没有初始化方法)。第一个线程来完成初始化设置延迟&LT的值; T&GT;
实例。该值将返回到被同时运行初始化方法的任何其他线程,除非初始化方法抛出的异常的这些线程。
When multiple threads try to initialize a
Lazy<T>
instance simultaneously, all threads are allowed to run the initialization method (or the default constructor, if there is no initialization method). The first thread to complete initialization sets the value of theLazy<T>
instance. That value is returned to any other threads that were simultaneously running the initialization method, unless the initialization method throws exceptions on those threads.
一个小code样品:</ P>
A little code sample:
var l = new Lazy<HashSet<string>>( () => new HashSet<string>() { "a" }
, LazyThreadSafetyMode.PublicationOnly
);
这篇关于是一个只读的HashSet天生线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!