5

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

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 发生时以某种方式被修改,则可能发生错误。

该错误是如此罕见且不可预测,以至于我们无法重新创建它,因此我们将不胜感激。

4

1 回答 1

1

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

并且 FirstOrDefault 可能只是 First 有时你有一个空列表,你有这个在 else 块上的后备

于 2016-12-27T13:16:16.027 回答