Alex Rivera | Logout

Is List<T> thread-safe for reading?

Asked 2011-08-05T11:52:40.627
39

Is the following pseudocode thread-safe ?

IList<T> dataList = SomeNhibernateRepository.GetData();

Parallel.For(..i..)
{
    foreach(var item in dataList)
    {
       DoSomething(item);
    }
}

The list never gets changed, it's only iterated and read in parallel. No writing to fields or something like that whatsoever.

Thanks.

Edit
Report

1 Answer

2

To make sure no one is going to change your list, you could access it through an IEnumerable

IEnumerable<T> dataList = SomeNhibernateRepository.GetData();

Parallel.For(..i..)
{
    foreach(var item in dataList)
    {
       DoSomething(item);
    }
}
answered 2011-08-05T11:59:38.723

Your Answer