间歇性 Linq First或默认错误 - 索引超出数组的边界

本文关键字:索引 数组 边界 错误 Linq First 默认 | 更新日期: 2023-09-27 18:34:50

大约每个月一次,我们遇到了一个奇怪的错误,我没有解释。 错误是这样的:

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)

下面是发生错误的代码。 此方法在 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);
}

当错误发生时,它将在此方法运行时 100% 发生(很多(,直到我回收应用程序池,从而修复它。 这向我表明它与此的缓存部分有关,但对我来说仍然没有意义,因为一旦我从缓存中提取 MyObjectList,就没有任何修改它,但似乎发生此错误的唯一方法是如果 MyObjectList 以某种方式被修改,而 firstordefault 正在发生。

该错误非常罕见且不可预测,以至于我们无法重新创建它,因此任何帮助将不胜感激。

间歇性 Linq First或默认错误 - 索引超出数组的边界

if (MyObjectList!= null)也许可以这样尝试 if (MyObjectList!= null && MyObjectList.Any(m => m.Id == this.Id)

FirstOrDefault 将只是 First 也许有时你有一个空列表,你在 else 块上有回退