約 1 か月に 1 回、説明のつかない奇妙なエラーが発生します。エラーは次のとおりです。
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 をプルすると何も変更されないため、まだ意味がありませんが、これが唯一の方法のようですfirstordefault が発生している間に MyObjectList が何らかの形で変更された場合、エラーが発生する可能性があります。
エラーは非常にまれであり、予測できないため、再現することができませんでした。