Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get expiry date for cached item?

Tags:

c#

asp.net

I store an object in MemoryCache:

void foo()
{
  ObjectCache cache = MemoryCache.Default;
  SomeClass obj = cache["CACHE_KEY"] as SomeClass;
  if (null == obj )
  {
     obj = new SomeClass(); ....
     CacheItemPolicy policy = new CacheItemPolicy();
     //update
     policy.AbsoluteExpiration = DateTime.Now+TimeSpan.FromMinutes(1);
     cache.Set("CACHE_KEY", obj, policy);
  }
  else
  {
     //get expiry date 
  }
  .....
}

Is it possible to get expiration date somehow if cache contains the object ?

like image 618
a1ex07 Avatar asked Jul 18 '11 20:07

a1ex07


2 Answers

Since you are setting the sliding expiration, isn't it always 10 minutes from the time you accessed it? if the object is null, the cache entry has expired and if not, the expiration (in the code above) is always 10 minutes from the time you checked?

Or you could have a base object (that all your cacheable objects inherits from) with the expiry time as a property that is set at the time you add to cache. When you extract the object, you check for the property and you have the expiration time to calculate the difference. Just a thought.

like image 132
coder net Avatar answered Nov 20 '22 04:11

coder net


As said, save expiry value once saving the object to memory cache,

cache.Set(DataKey, DataToStore, policy);
cache.Set("MemCacheExpiry", DateAndTime.Now.AddHours(6), policy);
        

Then read expiry from expiry key:

public static DateTime CheckCachedExpiry()
{
    DateTime MemCacheExpiryDate = default(DateTime);
    MemCacheExpiryDate = Convert.ToDateTime(MemoryCache.Default.Get("MemCacheExpiry"));
    return MemCacheExpiryDate;
}
like image 3
wpcoder Avatar answered Nov 20 '22 03:11

wpcoder