LIST<> AddRange抛出ArgumentException [英] LIST<> AddRange throwing ArgumentException
问题描述
我有一种特殊的方法偶尔会用ArgumentException崩溃:
I have a particular method that is occasionally crashing with an 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)
导致此崩溃的代码看起来如下所示:
The code that is causing this crash looks something like this:
List<MyType> objects = new List<MyType>(100);
objects = FindObjects(someParam);
objects.AddRange(FindObjects(someOtherParam);
根据MSDN,List<>。如果需要,AddRange()会自动调整自己的大小:
According to MSDN, List<>.AddRange() should automatically resize itself as needed:
如果新的Count(当前Count加上collection的大小)将大于容量,通过自动重新分配内部阵列以适应新的元素,增加List<(Of()的容量),并且现有元素在新元素之前被复制到新数组添加了
有人会想到AddRange可能会抛出此类异常的情况吗?
Can someone think of a circumstance in which AddRange could throw this type of exception?
编辑:
回答有关FindObjects()方法的问题。它基本上看起来像这样:
In response to questions about the FindObjects() method. It basically looks something like this:
List<MyObject> retObjs = new List<MyObject>();
foreach(MyObject obj in objectList)
{
if(someCondition)
retObj.Add(obj);
}
推荐答案
同一列表从多线程?这可能会导致问题... 列表< T>
对于多个作者是不安全的。
Are you trying to update the same list from multiple threads? That could cause problems... List<T>
isn't safe for multiple writers.
这篇关于LIST<> AddRange抛出ArgumentException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!