I have a main thread that populates a List<T>. Further I create a chain of objects that will execute on different threads, requiring access to the List. The original list will never be written to after it’s generated. My thought was to pass the list as IEnumerable<T> to the objects executing on other threads, mainly for the reason of not allowing those implementing those objects to write to the list by mistake. In other words if the original list is guaranteed not be written to, is it safe for multiple threads to use .Where or foreach on the IEnumerable?
I am not sure if the iterator in itself is thread safe if the original collection is never changed.
IEnumerable<T>can’t be modified. So what can be non thread safe with it? (If you don’t modify the actualList<T>).For non thread safety you need writing and reading operations.
“Iterator in itself” is instantiated for each
foreach.Edit: I simplified my answer a bit, but @Eric Lippert added valuable comment.
IEnumerable<T>doesn’t define modifying methods, but it doesn’t mean that access operators are thread safe (GetEnumerator,MoveNextand etc.) Simplest example:GetEnumeratorimplemented as this:IEnumeratorMore sophisticated example is caching.
This is interesting point, but fortunately I don’t know any standard class that has not thread-safe implementation of
IEnumerable.