在什么情况下System.Collections.ArrayList.Add会抛出IndexOutOfRangeException? [英] Under what circumstance System.Collections.ArrayList.Add throws IndexOutOfRangeException?

查看:354
本文介绍了在什么情况下System.Collections.ArrayList.Add会抛出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 ...

根据MSDN 添加方法应该只引用 NotSupportedException

According to the MSDN Add method should only throw NotSupportedException.

我不知道这里发生了什么。你是吗?

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

推荐答案

它归结为List不是线程安全的。在使用多个线程添加项目之前,如果没有同步,则在对列表进行迭代时发生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 as below,

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
}

在这种情况下,updatedFills计数被损坏,后续迭代失败。在锁定语句周围加上Add()应该可以避免这种情况。

In this case, updatedFills count gets corrupted and subsequent iteration fails. Wrapping the Add() around a lock statement should prevent this.

lock (updatedFills)
{
    updatedFills.Add(fill);
}

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆