C# 缓存过期

C# 缓存过期,c#,asp.net,.net,caching,C#,Asp.net,.net,Caching,如何控制asp.net中的缓存过期?我使用绝对过期,缓存每3小时过期一次。 现在我想添加一个条件,这样只有当条件为true时,缓存才会在3小时后过期。否则,如果条件为false,则缓存不应过期 我有办法做到这一点吗 我使用以下格式: ctx.Cache.Insert("cachename", cacheValue, null, DateTime.Now.AddHours(Int32.Parse(siteViewModel.ApplicationSettings

如何控制asp.net中的缓存过期?我使用绝对过期,缓存每3小时过期一次。 现在我想添加一个条件,这样只有当条件为true时,缓存才会在3小时后过期。否则,如果条件为false,则缓存不应过期

我有办法做到这一点吗

我使用以下格式:

ctx.Cache.Insert("cachename", cacheValue, null,
                  DateTime.Now.AddHours(Int32.Parse(siteViewModel.ApplicationSettings["CacheDurationHours"])), System.Web.Caching.Cache.NoSlidingExpiration, 
                 System.Web.Caching.CacheItemPriority.Default,
                 null
                 );

其中持续时间为3小时。因此缓存将在3小时内自动过期。有没有办法用条件控制过期时间?

您可以将cacheValue设置为检查条件的委托

ctx.Cache.Insert("cachename", () => condition? null : cacheValue, null,
    DateTime.Now.AddHours(
        Int32.Parse(siteViewModel.ApplicationSettings["CacheDurationHours"])),
    System.Web.Caching.Cache.NoSlidingExpiration,
    System.Web.Caching.CacheItemPriority.Default,
    null
);
然后要检索它,您可以使用

var del = ctx.Cache["cachename"] as Func<CacheValueType>;
if (del != null) cacheValue = del();
var del=ctx.Cache[“cachename”]作为函数;
如果(del!=null)cacheValue=del();

尽管更简单的方法是使用静态缓存,而不是缓存,只使用私有日期作为过期日期。

您可以将cacheValue设置为检查条件的委托

ctx.Cache.Insert("cachename", () => condition? null : cacheValue, null,
    DateTime.Now.AddHours(
        Int32.Parse(siteViewModel.ApplicationSettings["CacheDurationHours"])),
    System.Web.Caching.Cache.NoSlidingExpiration,
    System.Web.Caching.CacheItemPriority.Default,
    null
);
然后要检索它,您可以使用

var del = ctx.Cache["cachename"] as Func<CacheValueType>;
if (del != null) cacheValue = del();
var del=ctx.Cache[“cachename”]作为函数;
如果(del!=null)cacheValue=del();
虽然更简单的方法是使用静态而不是缓存,并且只使用私有日期作为过期日期。

那么:

DateTime absoluteExpiration = condition ? 
                  DateTime.UtcNow.AddHours(...) : 
                  Cache.NoAbsoluteExpiration;
ctx.Cache.Insert(..., absoluteExpiration, Cache.NoSlidingExpiration, ...);
顺便说一句,建议使用
DateTime.UtcNow
而不是
DateTime.Now
来计算绝对过期时间。

那么:

DateTime absoluteExpiration = condition ? 
                  DateTime.UtcNow.AddHours(...) : 
                  Cache.NoAbsoluteExpiration;
ctx.Cache.Insert(..., absoluteExpiration, Cache.NoSlidingExpiration, ...);
顺便说一句,建议使用
DateTime.UtcNow
而不是
DateTime.Now
来计算绝对过期时间