Talking about System.Collections.Generic.List<T>
here.
With example below can Method1 and Method2 execute and the same time, on different threads without any problems?
Thanks
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
}
}
}
Yes, List<T>
is safe to read from multiple threads so long as no threads are modifying the list.
From 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.
(The point about iterating being "intrinsically not a thread-safe procedure" is made in respect of something else mutating the list.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With