views:

100

answers:

2

More specifically, is List(T)(IEnumerable(T)) thread-safe if the IEnumerable used to initialize the list is modified during the construction of the new list?

+4  A: 

That has nothing to do with the List constructor being thread safe, it only depends on whether the IEnumerable is thread safe.

The constructor is not thread safe, but that is not a problem in this case. The constructor is not doing anything that compromises it's thread safety, it's the thread safety of the IEnumerable that may be a problem.

Guffa
There are special situations, but most constructors are naturally "thread safe". This is because other threads usually cannot obtain a reference to the object until after the constructor returns. This answer is entirely correct in saying that it depends on the specific IEnumerable<T> implementation.
binarycoder
Ok I suspected that this was the case but I wasn't quite sure since I made some performance comparisons of List<T>(IEnumerable<T>) and List<T>.AddRange(IEnumerable<T>) and the former seems to perform somewhat better than the latter. Thanks for the speedy answer!
scim
+1  A: 

This isn't really up to the list being constructed, but rather is up to the specific IEnumerable<T> being iterated. Is this thread safe? If it doesn't support concurrent iteration and edit, then expect an exception (or worse: unpredictable results). Most .NET iterators will not like this; 4.0 introduces more concurrent collections, or you can write your own.

If the list is createD successfully (iterating the source), then once constructed the origin has no impact - the two are disconnected.

Marc Gravell