是一个只读的HashSet天生线程? [英] Is a read-only HashSet inherently threadsafe?

查看:124
本文介绍了是一个只读的HashSet天生线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我初始化的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你可以肯定的延迟的初始化是线程安全的。

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 the Lazy<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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆