LIST <> AddRange抛出ArgumentException

Tim*_*Tim 9 c# exception list

我有一个特殊的方法偶尔崩溃与ArgumentException:

Destination array was not long enough. Check destIndex and length, and the array's lower bounds.:
at System.Array.Copy(Array sourceArray, Int32 sourceIndex, Array destinationArray, Int32 destinationIndex, Int32 length, Boolean reliable)
at System.Collections.Generic.List`1.CopyTo(T[] array, Int32 arrayIndex)
at System.Collections.Generic.List`1.InsertRange(Int32 index, IEnumerable`1 collection)
at System.Collections.Generic.List`1.AddRange(IEnumerable`1 collection)
Run Code Online (Sandbox Code Playgroud)

导致此崩溃的代码如下所示:

List<MyType> objects = new List<MyType>(100);
objects = FindObjects(someParam);
objects.AddRange(FindObjects(someOtherParam);
Run Code Online (Sandbox Code Playgroud)

根据MSDN,List <>.AddRange()应根据需要自动调整大小:

如果新的Count(当前Count加上集合的大小)将大于Capacity,则List <(Of <(T>)>)的容量会通过自动重新分配内部数组以适应新元素而增加,并且在添加新元素之前将现有元素复制到新数组.

有人可以想到AddRange会抛出这种类型的异常的情况吗?


编辑:

回答有关FindObjects()方法的问题.它基本上看起来像这样:

List<MyObject> retObjs = new List<MyObject>();

foreach(MyObject obj in objectList)
{
   if(someCondition)
       retObj.Add(obj);
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 21

您是否尝试从多个线程更新相同的列表?这可能会导致问题... List<T>对多个作家来说并不安全.

  • 你遇到的问题是肯定已经发生了,正如你所说,你有一个堆栈跟踪来证明它.我认为最有可能出现并发问题 - 例如,您确定它不是由UI按钮启动的后台任务,并且用户快速连续点击两次? (3认同)