mae*_*mbe 5 c# linq asp.net thread-safety asp.net-caching
大约每月一次,我们遇到了一个奇怪的错误,我没有解释.错误是这样的:
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)
Run Code Online (Sandbox Code Playgroud)
这是发生错误的代码.在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);
}
Run Code Online (Sandbox Code Playgroud)
当错误发生时,它将在100%的时间运行此方法(这很多),直到我回收应用程序池,修复它.这告诉我它与缓存部分有关,但它对我来说仍然没有意义,因为一旦我从缓存中拉出MyObjectList就没有任何修改它,但它似乎是唯一的方式如果在第一次失败发生时MyObjectList以某种方式被修改,则可能发生错误.
错误是如此罕见且不可预测,我们无法重新创建它,所以任何帮助将不胜感激.
if (MyObjectList!= null)也许尝试这样
if (MyObjectList!= null && MyObjectList.Any(m => m.Id == this.Id)
也许 FirstOrDefault 有时你有一个空列表,并且你在街区 First
有后备方案 else