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 ?
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With