- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
谈论System.Collections.Generic.List<T>
在这里。
通过下面的例子,Method1 和 Method2 可以在不同的线程上同时执行吗?
谢谢
class Test
{
private readonly List<MyData> _data;
public Test()
{
_data = LoadData();
}
private List<MyData> LoadData()
{
//Get data from dv.
}
public void Method1()
{
foreach (var list in _data)
{
//do something
}
}
public void Method2()
{
foreach (var list in _data)
{
//do something
}
}
}
最佳答案
是的,List<T>
从多个线程读取是安全的,只要没有线程修改列表。
来自 the docs :
A
List<T>
can support multiple readers concurrently, as long as the collection is not modified. Enumerating through a collection is intrinsically not a thread-safe procedure. In the rare case where an enumeration contends with one or more write accesses, the only way to ensure thread safety is to lock the collection during the entire enumeration. To allow the collection to be accessed by multiple threads for reading and writing, you must implement your own synchronization.
(关于迭代“本质上不是线程安全过程”的观点是针对其他改变列表的东西提出的。)
关于c# - 两个或多个线程可以毫无问题地迭代同一个 List<t> 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2637583/
我是一名优秀的程序员,十分优秀!