Is the List.AddRange() thread safe?

前端 未结 5 1709
天命终不由人
天命终不由人 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:12

    No, its documentation does not say it is thread safe, therefore it is not.

    Public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

    As to what can go wrong, think about what AddRange(newItems) does:

    • Check if there is enough space in the internal array
    • If not:
      • Allocate a new array
      • Copy the current items to the new array
      • Set a field to point at the new array
    • Copy the newItems to the correct local in the internal array
    • Update the “count” field (this is used to control where the next item is inserted)

    Now think what will happen if the above is mixed up with another call to AddRange() or even just a call to read an item.

提交回复
热议问题