bpe*_*aro 3 c# asp.net caching
我使用Http.Current.Cache存储从我的数据库中检索的各种值,因为我的应用程序是数据密集型的.在我的新笔记本电脑上使用VS2017安装运行我的网站时(在VS2015的另一台笔记本电脑上我从未见过这个问题),我看到一个非常奇怪的问题,其中缓存的值似乎被随机清除 - 几乎是以违反逻辑的方式.
例如,我有一个if子句,其条件是所讨论的缓存项不为null.我的代码肯定是通过这个if语句的路径,但稍后调试器显示缓存项实际上是空的 - 导致我的应用程序失败.
public static SportSeason GetCurrentSportSeason(string sportCode)
{
SportSeason sportSeason = null;
string key = "Sheets_SportSeason_" + sportCode;
int i = 0;
if (BaseSheet.Settings.EnableCaching && BizObject.Cache[key] != null)
{
i = 1;
sportSeason = (SportSeason)BizObject.Cache[key];
}
else
{
i = 2;
sportSeason = GetSportSeasonFromSportSeasonDetails(SiteProvider.Sheets.GetCurrentSportSeason(sportCode));
BaseSheet.CacheData(key, sportSeason);
}
if(sportSeason == null)
{
int j = i;
}
return sportSeason;
}
Run Code Online (Sandbox Code Playgroud)
我可以在final if中设置断点,并且变量i设置为1,但sportSeason对象为NULL(缓存条目也是如此).当代码进入第一个if子句的唯一方法是缓存项是否为空时,这怎么可能呢?
这很难追踪,因为它在我的业务对象中随机发生.在我看到这个问题之前,有时我必须刷新页面3到4次.
如何快速地使缓存失效,以及通过什么?屏幕截图显示缓存项目不多,所以我不认为我的内存不足.并且没有其他进程正在运行,这可能会破坏缓存.
编辑:通过更多调试,我确定只有在断点处再次检查时,才会清除第91行上检查的缓存键(设置为空).所有其他缓存记录仍然存在.
编辑2:我已经将问题归结为此,尽管它似乎仍然违背逻辑:
HttpContext.Current.Cache.Insert("ABC", "123", null, DateTime.Now.AddSeconds(600), TimeSpan.Zero);
int i = 0;
Run Code Online (Sandbox Code Playgroud)
我清除了所有缓存.当我跳过Cache.Insert语句时,我的缓存计数变为1.但是,根据该键的缓存项目保持为空(请参阅监视窗口).
此外,如果我再执行一个语句(int i = 0),则缓存计数将返回到零.
Edit3:这是杀死我的Insert()的AbsoluteExpiration参数.时钟已关闭.
如果我将AbsoluteExpiration设置为将来的5个小时(300分钟),它就不起作用.如果我将它设置为未来5小时1分钟(301分钟),一切正常.
HttpContext.Current.Cache.Insert("ABC", "123", null, DateTime.Now.AddMinutes(301), TimeSpan.Zero);
Run Code Online (Sandbox Code Playgroud)
我的笔记本电脑上的时钟是100%准确的,您可以看到Intellisense也显示正确的时间.缓存是否可以基于5小时的其他时钟?
编辑4:看起来其他人已经关闭了5个小时.
修复是始终使用DateTime.在指定AbsoluteExporation参数时,Utc Now而不是DateTime.Now.
做这个:
HttpContext.Current.Cache.Insert("ABC", "123", null, DateTime.UtcNow.AddMinutes(1), System.Web.Caching.Cache.NoSlidingExpiration);
Run Code Online (Sandbox Code Playgroud)
不是这个:
HttpContext.Current.Cache.Insert("ABC", "123", null, DateTime.Now.AddMinutes(1), System.Web.Caching.Cache.NoSlidingExpiration);
Run Code Online (Sandbox Code Playgroud)
当我这样做时,它正确识别缓存有效,我可以检索该值.至于为什么在我的Windows 10 Pro笔记本电脑上需要这个,而不是在我的Windows 10 Home上,我不知道.