Search code examples
c#exceptiongeneric-listaddrange

Argument Exception thrown by Generic.List when using AddRange with an empty Generic.List as argument


In my program I'm getting an unhandled System.ArgumentException when trying to use the AddRange function:

Destination Array was not long enough. Check destIndex and length, and the array's lower bounds.

When debugging, I break on the exception on my row:

ListA.AddRange(ListB);

In the watch tool by the debugger I can see that:

ListA: Count = 2454
ListB: Count = 0

Looking at the documentation for a generic list, the ArgumentException is not listed.

Am I missing anything when trying to pin-point what exactly is going wrong?


Solution

  • List<T> is not thread-safe. From the docs:

    Thread Safety

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

    It is safe to perform multiple read operations on a List, but issues can occur if the collection is modified while it's being read. To ensure thread safety, lock the collection during a read or write operation. To enable a collection to be accessed by multiple threads for reading and writing, you must implement your own synchronization. For collections with built-in synchronization, see the classes in the System.Collections.Concurrent namespace. For an inherently thread-safe alternative, see the ImmutableList class.

    It is not safe to write to a List<T> at the same time from multiple threads, or to write to a List<T> on one thread while reading from it on another thread. You will see random "unexplained" exceptions, like the one you're seeing.

    Use a lock to properly synchronize access to your list, use a thread-safe collection, or re-architect so you don't need to do this.