安装 .NET Framework 4.7 后,Cache.Insert() 设置的缓存自动过期变成永不过期了

本文发布于 7 年前,部分内容可能已经失去参考价值。

经测试,.NET Framework 4.8 的 Cache.Insert() 已恢复正常。

安装 .NET Framework 4.7 后,不管项目有没有升级到 .NET Framework 4.7,使用 Cache.Insert() 添加的自动过期的缓存都不会过期了,可以使用 Cache.Add() 来解决!

使用 Cache.Insert() 例:

HttpRuntime.Cache.Insert(key, value, null, DateTime.Now.AddSeconds(5), Cache.NoSlidingExpiration);

改为使用 Cache.Add():

HttpRuntime.Cache.Add(key, value, null, DateTime.Now.AddSeconds(5), Cache.NoSlidingExpiration, CacheItemPriority.Default, null);

如果 Cache 中已保存了具有相同 key 的项,则调用 Add 方法将不作任何更改。(Insert 方法则会覆盖该值)


完整测试代码:

public static DateTime DateTimeNow
{
    get
    {
        if (HttpRuntime.Cache["DateTimeNow"] == null)
        {
            HttpRuntime.Cache.Add("DateTimeNow", DateTime.Now, 
                null, DateTime.Now.AddSeconds(5), Cache.NoSlidingExpiration, 
                CacheItemPriority.Default, null);
        }
        return Convert.ToDateTime(HttpRuntime.Cache["DateTimeNow"]);
    }
}


在部分项目中(如 .NET Framework 4 项目中)发现上述改动仍不起作用,不会自动过期,那么可以采用以下方法:


方法一、可以记录将数据添加到 Cache 的时间,获取数据时判断该时间,超时则清除该 Cache 并重新赋值;

方法二、放弃缓存依赖,用定时器清除 Cache 数据。

xoyozo 7 年前
转载请注明出处
云服务器 精选特惠
可能相关的内容