问题描述
我们在生产环境中遇到了奇怪的错误,我们无法调试也无法注入日志代码.我试图弄清楚这一点,但跟踪堆栈跟踪让我感到困惑.
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 ...
根据MSDN Add
方法应该只抛出 NotSupportedException
.
According to the MSDN Add
method should only throw NotSupportedException
.
我不知道这里发生了什么.你呢?
I have no idea what's going on here. Do you?
推荐答案
归结为 List 不是线程安全的.我在使用多个线程添加项目后遍历列表时发生了IndexOutOfRangeException,没有同步.下面的代码可能会破坏项目计数并在随后迭代列表时导致 IndexOutOfRangeException,
It boils down to List not being thread safe. I have had IndexOutOfRangeException occuring when iterating over a list after adding items using multiple threads without synchronization. The code below could corrupt the items count and result in IndexOutOfRangeException while iterating the list subsequently,
List<TradeFillInfo> updatedFills = new List<TradeFillInfo>();
Parallel.ForEach (trades, (trade) =>
{
TradeFillInfo fill = new TradeFillInfo();
//do something
updatedFills.Add(fill); //NOTE:Adding items without synchronization
});
foreach (var fill in updatedFills) //IndexOutOfRangeException here sometimes
{
//do something
}
将 Add() 与 lock 语句同步将解决该问题.
Synchronizing the Add() with a lock statement will fix the issue.
lock (updatedFills)
{
updatedFills.Add(fill);
}
这篇关于System.Collections.ArrayList.Add 在什么情况下会抛出 IndexOutOfRangeException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!