Is the List.AddRange() thread safe?

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

    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. =)

提交回复
热议问题