views:

144

answers:

2

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
        }
    }
}
+15  A: 

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

Jon Skeet
A: 

You can use the iterators gotten by the foreach() just fine on multiple threads. As long as you don't add or remove elemnts from the list, you should be fine. I believe that you even get to modify the members of whatever your is, but this takes you into non-thread-safe territory.

LaustN