gpt4 book ai didi

c# - 两个或多个线程可以毫无问题地迭代同一个 List 吗?

转载 作者:可可西里 更新时间:2023-11-01 08:18:36 24 4
gpt4 key购买 nike

谈论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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com