.net MemoryCache - notify on item removed

DermFrench picture DermFrench · Apr 8, 2014 · Viewed 9.2k times · Source

I'm using a .net Memory Cache with .NET 4.0 and c#, I want my application to be notified when an item is removed (so I can write that it has been removed to a log file or notify the UI, that the item is removed).

Is there anyway to do this.

I'm using System.Runtime.Caching.MemoryCache not System.Web.Caching

Answer

samy picture samy · Apr 8, 2014

EDIT: If you're using the System.Runtime.Caching.MemoryCache there is a callback on the CacheItemPolicy object for deletion, as well as one for update.

myMemoryCache.Set("key", null, new CacheItemPolicy() {RemovedCallback = new CacheEntryRemovedCallback(CacheRemovedCallback) /* your other parameters here */});

public void CacheRemovedCallback(CacheEntryRemovedArguments arguments)
{
    // do what's needed
}

Initial answer

When inserting data in the .net cache for the System.Web.Caching namespace you have the option to set a callback to be notified of removal

Cache.Insert("data", "", null, DateTime.Now.AddMinutes(1), System.Web.Caching.Cache.NoSlidingExpiration, CacheItemPriority.High, new CacheItemRemovedCallback(CacheRemovedCallback));

public string CacheRemovedCallback(String key, object value, System.Web.Caching.CacheItemRemovedReason removedReason)
{
    // here you can log, renew the value, etc...
}

There is also a signature for the Insert method that lets you specify a callback to be notified before the item is removed