Linq中的FirstOrDefault错误:数组索引超出范围的间歇性问题 您所在的位置:网站首页 list索引超出范围 Linq中的FirstOrDefault错误:数组索引超出范围的间歇性问题

Linq中的FirstOrDefault错误:数组索引超出范围的间歇性问题

2023-03-27 19:19| 来源: 网络整理| 查看: 265

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

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 MyObjectList= System.Web.HttpRuntime.Cache["MyObjects"] as List; 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(); //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以某种方式被修改,则可能发生错误.

错误是如此罕见且不可预测,我们无法重新创建它,所以任何帮助将不胜感激.



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有