Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is List<T> thread-safe for reading?

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.

like image 948
user315648 Avatar asked Aug 05 '11 11:08

user315648


People also ask

Does list contain thread-safe?

If a writer may be writing at the same time, List. Contains is definitely not thread safe. You'll need to wrap it and any other reads and writes with a lock.

Is .NET list thread-safe?

NET Framework 4 introduces the System. Collections. Concurrent namespace, which includes several collection classes that are both thread-safe and scalable. Multiple threads can safely and efficiently add or remove items from these collections, without requiring additional synchronization in user code.

Why are lists not thread-safe?

In fact, by default, classes are not thread-safe. Being thread-safe would mean that any operation modifying the list would need to be interlocked against simultaneous access. This would be necessary even for those lists that will only ever be used by a single thread. That would be very inefficient.

How can you tell if a thread is safe?

To test if the combination of two methods, a and b, is thread-safe, call them from two different threads. Put the complete test in a while loop iterating over all thread interleavings with the help from the class AllInterleavings from vmlens. Test if the result is either an after b or b after a.


1 Answers

Yes, List<T> is fine to read from multiple threads concurrently, so long as nothing's writing.

From the documentation:

A List<T> can support multiple readers concurrently, as long as the collection is not modified.

EDIT: Note that your code doesn't necessarily use List<T> - just an IList<T>. Do you know the type returned by GetData()? If you're in control of GetData() you probably want to document that the list returned by it is thread-safe for reading, if it's actually returning a List<T>.

like image 68
Jon Skeet Avatar answered Sep 28 '22 03:09

Jon Skeet