为list< T>线程安全的阅读? [英] Is List<T> thread-safe for reading?
问题描述
为以下伪线程安全的。
IList<T> dataList = SomeNhibernateRepository.GetData();
Parallel.For(..i..)
{
foreach(var item in dataList)
{
DoSomething(item);
}
}
永远不会被改变的列表,它只是重复和阅读在平行下。没有书面的字段或类似的任何东西。
The list never gets changed, it's only iterated and read in parallel. No writing to fields or something like that whatsoever.
感谢。
推荐答案
是列表< T>
是好的,从多个线程同时读,只要没有什么写作
Yes, List<T>
is fine to read from multiple threads concurrently, so long as nothing's writing.
文档:
A 列表< T>
可以支持多个读者同时,只要收集不修改
A
List<T>
can support multiple readers concurrently, as long as the collection is not modified.
编辑:请注意,您的代码不会的不一定的使用列表< T>
- 只是一个的IList< T>
。你知道通过返回的类型的GetData()
?如果你是在控制的GetData()
你可能想记录,通过它返回的列表是线程安全的阅读,如果它实际上返回列表< T>
Note that your code doesn't necessarily use List<T>
- just an IList<T>
. Do you know the type returned by GetData()
? If you're in control of GetData()
you probably want to document that the list returned by it is thread-safe for reading, if it's actually returning a List<T>
.
这篇关于为list< T>线程安全的阅读?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!