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.
Yes,
List<T>is fine to read from multiple threads concurrently, so long as nothing’s writing.From the documentation:
EDIT: Note that your code doesn’t necessarily use
List<T>– just anIList<T>. Do you know the type returned byGetData()? If you’re in control ofGetData()you probably want to document that the list returned by it is thread-safe for reading, if it’s actually returning aList<T>.