Wire Up Your Own Cache Expiration Callbacks
Implement asynchronous notifications using delegates and the ASP.NET Caching API.
by Jonathan Goodyear
One of the greatest caching features implemented in ASP.NET is the ability to assign a callback function that gets fired when an item is removed or expired from the cache. I'll tell you how it all works, and show you how to wire up your own cache expiration callback. If you need more detail on ASP.NET caching, you can check out Dino Esposito's "Cache and Carry With ASP.NET" article from a couple months back [ASP.NET column, Visual Studio Magazine November 2001].
You enable cache expiration callbacks through the use of the CacheItemRemovedCallback delegate. In the .NET Framework, function pointers get implemented through delegates. Wiring up a cache removal callback involves three steps:
First, declare a delegate function you'd like to have called when your cached item is removed.
Second, create an instance of the CacheItemRemovedCallback delegate, using the delegate function you created in step 1 in the constructor.
And third, use the instance of the CacheItemRemovedCallback delegate you created in step 2 in the call to insert your item into Cache.
Start out by creating a simple ASP.NET Web Form (see Listing 1). It implements two TextBox server controls (keyBox and valueBox) and two Button server controls (addCacheItem and checkStatus). The script block at the top of the listing references these controls. Note that this code example does not use a code-behind class, and implements the page-processing logic at the top of the ASPX page itself.
The script block begins by implementing the Page_Init event. This event is used to wire up the Click events for the buttons on your Web Form. Next is the delegate function implementation of the CacheItemRemovedCallback delegate. For the purposes of this demo, the function merely sets another item named CacheStatus in Cache, indicating the key and value of the item that was removed from Cache, as well as the reason for its removal. In a production environment, you would most likely want to implement code to refresh the item in Cache so that it will be immediately available when it is requested again.
Back to top
|