Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intermittent Linq FirstOrDefault Error - Index was outside the bounds of the array

About once a month, we've been running into a bizarre error that I have no explanation for. The error is this:

System.IndexOutOfRangeException: Index was outside the bounds of the array.
at System.Collections.Generic.List`1.Enumerator.MoveNext() at 
System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable`1 source, Func`2   predicate)

Here's the code where the error is happening. This method is called in the constructor of MyObject:

// pull a list of MyObjects from the cache so we can see if this one exists
List<MyObject> MyObjectList= System.Web.HttpRuntime.Cache["MyObjects"] as   List<MyObject>;
if (MyObjectList!= null)
{
     // this is where the error happens.  Just getting an object out based on its id
     MyObject obj = MyObjectList.FirstOrDefault(m => m.Id == this.Id);

     if(obj != null){
         // great, it already exists in the cache
     }
     else{
         // doesn't exist in the cache, query the database and then add it to the cache
          //add it to the cache after loading from db
          MyObjectList.Add(this);
          System.Web.HttpContext.Current.Cache.Insert("MyObjects",MyObjectList);
     }
}
else{
    // instantiate a new list, query the db for this object, add it to the list and add the list to the cache
    MyObjectList= new List<MyObject>();

    //add it to the cache after it was loaded from the db
    MyObjectList.Add(this);
    System.Web.HttpContext.Current.Cache.Insert("MyObjects",MyObjectList);
}

When the error happens, it will happen 100% of the time when this method runs (which is a lot) until I recycle the app pool, which fixes it. This suggests to me that it has something to do with the caching part of this, but it still doesn't make sense to me, since once I pull MyObjectList from the cache there is nothing modifying it, but it seems like the only way this error could happen would be if MyObjectList was somehow being modified while firstordefault was happening.

The error is so infrequent and not predictable that we haven't been able to recreate it, so any help would be greatly appreciated.

like image 798
maembe Avatar asked Nov 08 '22 20:11

maembe


1 Answers

if (MyObjectList!= null) maybe try like this if (MyObjectList!= null && MyObjectList.Any(m => m.Id == this.Id)

and FirstOrDefault will be just First maybe sometimes u have an empty list and u have fallback for this on the else block

like image 103
Alex Banu Avatar answered Nov 14 '22 22:11

Alex Banu