Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
428 views
in Technique[技术] by (71.8m points)

.net - Under what circumstance System.Collections.ArrayList.Add throws IndexOutOfRangeException?

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 to the MSDN Add method should only throw NotSupportedException.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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."

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...