是列表<T>线程安全的阅读? [英] Is List&lt;T&gt; thread-safe for reading?

查看:23
本文介绍了是列表<T>线程安全的阅读?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的伪代码是线程安全的吗?

Is the following pseudocode thread-safe ?

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.

谢谢.

推荐答案

是的,List 可以从多个线程并发读取,只要什么都不写.

Yes, List<T> is fine to read from multiple threads concurrently, so long as nothing's writing.

来自文档:

一个List可以同时支持多个阅读器,只要不修改集合即可.

A List<T> can support multiple readers concurrently, as long as the collection is not modified.

请注意,您的代码并不必然使用 List - 只是一个 IList.你知道 GetData() 返回的类型吗?如果您控制 GetData(),您可能想要记录它返回的列表对于读取是线程安全的,如果它实际上返回的是 List>.

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>.

这篇关于是列表<T>线程安全的阅读?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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