Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can two or more threads iterate over the same List<t> without any problems?

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
        }
    }
}
like image 275
CodingCrapper Avatar asked Apr 14 '10 13:04

CodingCrapper


1 Answers

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

like image 158
Jon Skeet Avatar answered Sep 29 '22 23:09

Jon Skeet