Add抛出IndexOutOfRangeException

Add抛出IndexOutOfRangeException

本文介绍了在什么情况下System.Collections.ArrayList.Add抛出IndexOutOfRangeException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正经历着奇怪的错误,在生产环境中,我们无法调试,也注入日志code。我想弄清楚这件事,但以下堆栈跟踪迷惑我。

We are experiencing weird bug at production environment we cannot debug nor inject logging code. I am trying to figure this up but following stack trace confuse me.

System.IndexOutOfRangeException: Index was outside the bounds of the array.
   at System.Collections.ArrayList.Add(Object value)
   at ...

According到MSDN 添加方法应该只抛出 NotSupportedException异常

According to the MSDN Add method should only throw NotSupportedException.

我不知道是怎么回事。你知道吗?

I have no idea what's going on here. Do you?

推荐答案

的<$c$c>IndexOutOfRangeException当试图访问一个数组的一个元素的索引,它是数组的范围之外。被抛出

The IndexOutOfRangeException is thrown when "an attempt is made to access an element of an array with an index that is outside the bounds of the array."

注意的ArrayList 类不是线程安全的。这可能是在多线程的情况,种族条件将导致的ArrayList 尝试读/写支持数组索引处是的范围之外。

Note that the ArrayList class is not thread-safe. It is possible that in multi-threaded scenarios, race-conditions will result in the ArrayList attempting to read/write to the backing array at indices that are outside its range.

例:一个线程降低了支持数组(也许是通过一个 TrimToSize 调用)在另一个线程也加入到了集合的同时大小。现在,如果支持数组处于满负荷生产,增加线程会试图扩大其产能(通过分配一个新的数组),以适应新的元素。同时 TrimToSize 调用然后反转这种效果。然后,由当时的增加线程试图写入到阵列中,索引,它的认为的是可利用的将不再是,导致异常被抛出。

Example: One thread reduces the size of the backing array (perhaps through a TrimToSize call) at the same time that another thread is adding to the collection. Now, if the backing array is at full capacity, the adding thread will attempt to expand its capacity (by allocating a new array) to accomodate the new element. The simultaneous TrimToSize call then reverses this effect. Then, by the time the adding thread attempts to write to the array, the index that it thought was available would no longer be, causing the exception to be thrown.

修正:使用线程安全的结构,如适当的的情况

Fix: Use thread-safe constructs, as appropriate to your situation.

这篇关于在什么情况下System.Collections.ArrayList.Add抛出IndexOutOfRangeException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 23:01