Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET 4 ObjectCache - Can We Hook Into a "Cache Expired" Event?

I've got a simple object being cached like this:

_myCache.Add(someKey, someObj, policy);

Where _myCache is declared as ObjectCache (but injected via DI as MemoryCache.Default), someObj is the object i'm adding, and policy is a CacheItemPolicy.

If i have a CacheItemPolicy like this:

var policy = new CacheItemPolicy 
{ 
   Priority = CacheItemPriority.Default, 
   SlidingExpiration = TimeSpan.FromHours(1)
};

It means it will expire in 1 hour. Cool.

But what will happen is that unlucky first user after the hour will have to wait for the hit.

Is there any way i can hook into an "expired" event/delegate and manually refresh the cache?

I see there is a mention of CacheEntryChangeMonitor but can't find any meaninful doco/examples on how to utilize it in my example.

PS. I know i can use CacheItemPriority.NotRemovable and expire it manually, but i can't do that in my current example because the cached data is a bit too complicated (e.g i would need to "invalidate" in like 10 different places in my code).

Any ideas?

like image 980
RPM1984 Avatar asked Oct 05 '11 04:10

RPM1984


People also ask

What happens when cache expires?

It means that a cache should not return the response-entity after that time, unless it is first validated against the origin server. The value of the Expires date/time can cause the following specific cache behavior: When the Expires date is equal to the Date header value, the response is considered to be expired.

What is in-memory cache in C#?

IMemoryCache represents a cache stored in the memory of the web server. Apps running on a server farm (multiple servers) should ensure sessions are sticky when using the in-memory cache. Sticky sessions ensure that requests from a client all go to the same server.


1 Answers

There's a property on the CacheItemPolicy called RemovedCallback which is of type: CacheEntryRemovedCallback. Not sure why they didn't go the standard event route, but that should do what you need.

http://msdn.microsoft.com/en-us/library/system.runtime.caching.cacheitempolicy.removedcallback.aspx

like image 108
BFree Avatar answered Oct 24 '22 16:10

BFree