Reputation: 305
How can I control the cache expiration in asp.net? I use absolute expiration and the cache expires every 3 hours. NOw I want to add a condition, so that only if the condition is true, the cache should expire at the end of 3 hours. Else, if the condition is false , the cache should not expire.
Is there a way I can do this?
I am using the following format:
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
);
where the duration is 3 hours. So the cache expires automatically in 3 hours. is there a way to control the expiration with a condition?
Upvotes: 0
Views: 11077
Reputation: 124696
What about:
DateTime absoluteExpiration = condition ?
DateTime.UtcNow.AddHours(...) :
Cache.NoAbsoluteExpiration;
ctx.Cache.Insert(..., absoluteExpiration, Cache.NoSlidingExpiration, ...);
BTW the MSDN description of the absoluteExpiration parameter recommends using DateTime.UtcNow
rather than DateTime.Now
to calculate the absolute expiration.
Upvotes: 4
Reputation: 68687
You could make the cacheValue a delegate which checks the condition
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
);
And then to retrieve it, you would use something along the lines of
var del = ctx.Cache["cachename"] as Func<CacheValueType>;
if (del != null) cacheValue = del();
Although an easier way is to use a static rather than the cache, and just a private date as expiration.
Upvotes: 1