Is the List.AddRange() thread safe?

前端 未结 5 1715
天命终不由人
天命终不由人 2021-02-07 09:14

Can I, without locking, safely call List.AddRange(r) from multiple threads? If not, what sort of trouble would I run into?

5条回答
  •  心在旅途
    2021-02-07 10:02

    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.

提交回复
热议问题