Can I, without locking, safely call List.AddRange(r) from multiple threads? If not, what sort of trouble would I run into?
No it's not, but I'd like to add it's more efficient to do an myList.AddRange(...);
within a lock than doing several lock (syncLock) { myList.Add(...) };
.
Which sort of trouble would you run into? When one thread is adding an item while another is enumerating the list, List
will throw a certain exception because it does some internal versioning, as it wants to prevent us poor developers from hitting nasty side effects.
Also the List
internally keeps an array in which it stores its items. Maybe setting an item in an array is pretty atomic, but whenever the capacity of this array is reached, a new one will be created and the items will be copied over from the old one. So when a thread wants to add something while that copying takes place, you can imagine that things would go out of sync.