Alex Rivera | Logout

Is the List<T>.AddRange() thread safe?

Asked 2010-10-28T14:06:53.393
17

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

Edit
Report

2 Answers

19

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.

answered 2010-10-28T14:09:37.197
3

Until .NET Framework 4.0, no .NET collections are thread-safe. You will then be required to lock it before you access it in your code Collections and Synchronization (Thread Safety).

On the other hand, .NET Framework 4.0 introduces the new System.Collections.Concurrent namespace which includes fine-grained Thread-Safe Collections.

Finally, if you can use .NET Framework 4.0, I strongly recommend you do so for what you need, otherwise, make sure to lock the collection each time you want to modify or access it.

Besides, a static collection should be thread-safe, but beware, as the members are not guaranteed to be.

EDIT #1

After further verifications due to Steve Townsend's comment, I admit that there are three thread-safe collections within the .NET Framework starting with version 3.0:

  1. SynchronizedCollection Generic Class;
  2. SynchronizedKeyedCollection Generic Class;
  3. SynchronizedReadOnlyCollection Generic Class.

I apologize, I just learned their exitense myself. =)

answered 2010-10-28T14:19:26.650

Your Answer