简体   繁体   English

将项目添加到通用列表时,“索引超出了数组的范围”

[英]“Index was outside the bounds of the array” when adding an item to a generic list

I just had a unique error where a live site was throwing "Index was outside the bounds of the array" on login. 我只是遇到了一个独特的错误,一个实时网站在登录时抛出了“索引超出数组范围”的错误。 I tracked the error down to an old "timing" file inherited from an old project. 我将错误跟踪到了从旧项目继承的旧“ timing”文件。 Here's the full class 这是全班

public class TimingObject
{
    public DateTime timestamp { get; set; }
    public String call { get; set; }
    public TimeSpan duration { get; set; }

    // create a new timing object starting now
    public TimingObject()
    {
        timestamp = DateTime.Now;
    }

    public TimingObject(String call)
    {
        timestamp = DateTime.Now;
        this.call = call;
    }

    public void Stop()
    {
        List<TimingObject> timings;
        if (HttpContextManager.Current.Cache["PageTimings"] == null)
            timings = new List<TimingObject>();
        else
            timings = HttpContextManager.Current.Cache["PageTimings"] as List<TimingObject>;
        this.duration = (DateTime.Now - this.timestamp);
        timings.Add(this);
        HttpContextManager.Current.Cache["PageTimings"] = timings;
    }
}

The error was thrown by timings.Add(this) . 该错误是由timings.Add(this)抛出的。 Why would Index was out of bounds be thrown when adding an item to a list? 项目添加到列表时Index was out of bounds为什么Index was out of bounds

Could this happen if the list is too big? 如果列表太大,会发生这种情况吗? And how big would it have to be exactly? 而且它到底有多大?

The code is redundant, and has been removed. 该代码是冗余的,已被删除。 But I'd really like to know why this happened. 但是我真的很想知道为什么会这样。

List<T> is not thread safe, and this code looks suspiciously like you would be fetching a shared instance of List<T> from multiple threads. List<T>不是线程安全的,并且此代码看起来可疑,就像您将从多个线程中获取List<T>的共享实例一样。 I suspect you are adding to the list from two different threads simultaneously and throwing off the array that is making the List work under the covers. 我怀疑您是同时从两个不同的线程添加到列表,并抛出使List在后台运行的数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM