Cache expiration

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?

Answers


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.


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.


Need Your Help

ms access query results display problems

ms-access

I'm trying to produce a list of names and addresses of our clients that have paid within a particular timeframe.

Trouble casting lambda to std::function

c++ visual-studio-2012 c++11 lambda mingw

I'm having trouble with MiniGW when attempting to create an API. This works fine in MSVC11 (Visual Studio 2012 C++ compiler). My compiler (I believe) is set up properly QMAKE_CXXFLAGS += -std=c++0x,