// Re-fetch data
// ... DataSet ds = ....
"myDataSet", ds, null, System.Web.Caching.Cache.NoAbsoluteExpiration, System.Web.Caching.Cache.NoSlidingExpiration
Great thing! But... What if I want to centralise cache creation? What if I want to log something everytime a cache item has been removed due to memory limits being reached? Luckily, ASP.NET provides an answer to that: the System.Web.Caching.CacheItemRemovedCallback delegate. This delegate can be used to ask ASP.NET to notigy you using a delegate of what is happening inside the cache when something is removed from it. Here's the delegate signature:
void (string key, Object value, CacheItemRemovedReason reason);
As you can see, you can get the key that's being removed, its current value, and the reason why the item is being deleted. These reasons can be: Expired, Removed, Underused, and DependencyChanged. I think these speak for themselves, no?
Now let's implement this: I'll create a CacheRetrievalManager which will update my cache whenever an item is removed from cache:
public class CacheRetrievalManager
public void RemovedCacheItemHandler(string key, Object value, CacheItemRemovedReason reason)
// call method to re-fetch data and re-set cache
One thing left is to specify that this method should be called whenever a cache item is removed:
// Insert in cache ONCE, recreation will be handled by CacheRetrievalManager
DataSet ds = ...;
"myDataSet", ds, null, System.Web.Caching.Cache.NoAbsoluteExpiration, System.Web.Caching.Cache.NoSlidingExpiration, CacheRetrievalManager.RemoveCacheItemHandler
Now I know exactly why something is removed, and that I can even log when this happens. You can now further extend this into separate CacheRetrievalManagers for every object you which to cache, fetch data inside that manager, ...
This is an imported post. It was imported from my old blog using an automated tool and may contain formatting errors and/or broken images.