Linq Abort Error FirstOrDefault - Index Was Out of Array

About once a month we came across a bizarre mistake that I have no explanation about. 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 is the code in which the error occurs. 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 an error occurs, it will happen in 100% of cases when this method is started (which is a lot), until I process the application pool that fixes it. This tells me that this has something to do with the caching part of it, but it still makes no sense to me, because as soon as I pull MyObjectList from the cache, it doesn't modify anything, but it seems like this is the only way an error can occur if MyObjectList was somehow modified and firstordefault occurred.

The error is so rare and unpredictable that we could not recreate it, so any help would be greatly appreciated.

+5
source share
1 answer

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

and FirstOrDefault will be just First perhaps, sometimes you have an empty list, and you have a reserve for this in the else block

+1
source

Source: https://habr.com/ru/post/1243067/


All Articles