Pattern for ASP.NET Cache and the new Cache.Insert overload in 3.5 SP1
David Penton, a fellow AspInsider, has published an excellent article on AspAlliance how to take pattern-like approach to ASP.NET cache
A New Approach to HttpRuntime.Cache Management
http://aspalliance.com/1705_A_New_Approach_to_HttpRuntimeCache_Management
In the article David covers how to approach the two most common issues with ASP.NET Cache, that is how to deal with the first hit in thread-safe, CPU-safe and database friendly manner and the other is how to do repopulation in the background. It is important to realize that populating the cache on the first hit can easily be a performance hog if it isn't understood how ASP.NET actually runs multiple threads as it handles simultaneous requests. You might end up with multiple threads trying to do the initial populating of cache which basically is a waste of resources, and depending on your app, might be unacceptable.
After the data is in the cache and expires for the first time, comes the background populating task/issue and to complement the options, ASP.NET 3.5 SP1 brings an exciting new feature which is a new overload in Cache.Insert[1] which makes it possible for user code to be notified before item will be removed from cache. Note that till pre-SP1 you've got the notification after the item is already expired. The new overload looks like
void Cache.Insert( String key,
Object expensiveObject,
CacheDependency dependencies,
DateTime absoluteExpiration,
TimeSpan slidingExpiration,
CacheItemUpdateCallback onUpdateCallback
);
and the signature of callback method dictated by CacheItemUpdateCallback
void CacheItemUpdateCallback( String key,
CacheItemUpdateReason reason,
out Object expensiveObject,
out CacheDependency dependencies,
out DateTime absoluteExpiration,
out TimeSpan slidingExpiration
);
There's a few things to pay attention to when using this approach and I suggest you have a look at the referenced blog post by Thomas Marquardt to understand all the bells and whistles.
[1] Source and reference: http://blogs.msdn.com/tmarq/archive/2008/07/22/asp-net-cache-can-notify-you-before-an-entry-is-removed.aspx