How to get expiry date for cached item?

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;
}

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.

Tags:

C#

Asp.Net