![](/img/trans.png)
[英]C# List.AddRange in Parallel.For occur ArgumentException
[英]LIST<> AddRange throwing ArgumentException
我有一個特殊的方法偶爾崩潰與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)
導致此崩潰的代碼如下所示:
List<MyType> objects = new List<MyType>(100);
objects = FindObjects(someParam);
objects.AddRange(FindObjects(someOtherParam);
根據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);
}
您是否嘗試從多個線程更新相同的列表? 這可能會導致問題...... List<T>
對多個編寫者來說並不安全。
老實說,我不確定,但為什么不刪除列表初始化中的大小聲明?
List`<MyType>` list = new List`<MyType>`
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.