简体   繁体   中英

“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. 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) . Why would Index was out of bounds be thrown when adding an item to a list?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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