Recommended hosting
Aug 30 2006

ASP.NET - caching control

Posted by admin under ASP.NET articles

The ASP.NET cache is simply fantastic, but there are some shortcomings. While it is so easy to create a cache item dependent on, say for example a XML file (meaning the cache item will expire when the file xxx.xml is changed) it is not so common for such scenarios in my opinion. Also, now in .NET 2.0 you can create SqlCacheDependencys, meaning an cached item will be expired (and therefore a fresh read fromthe database will be executed) when something in the database is changed (could be set on query level actually).

However, to me such solutions are so much overkill, lots of overhead and also (for SqlCacheDependency ) you tie your solution pretty much to SQL 2005.
Most often you just want to cache some data in your application, example

string sTxt = "";
if ( context.Cache["RSSFEED123"] == null )
{
	sTxt = BuildXmlString(context);
	context.Cache.Insert( "RSSFEED123", sTxt, ..some depencency object... );
}
else
	sTxt = context.Cache["RSSFEED123"].ToString();

work with txt...

My point is that most often YOU have the control of knowing when the Cache item should expire. In 99.99% of my cases it should trigger when an administrator enters a new/changes an existing article or whatever in the admin GUI.
So, my solution (here I show it with no cachedependency at all, living for the lifetime of the whole application) but you can of course use it in conjunction with a cachedependency.

Code using it:
 
string sTxt = "";
if ( context.Cache["RSSFEED123"] == null )
{
	sTxt = BuildXmlString(context);
	context.Cache.Insert( "RSSFEED123", sTxt );
}
else
	sTxt = context.Cache["RSSFEED123"].ToString();


Admin GUI:
private void btnUpdate_Click(object sender, System.EventArgs e)
{
	//Save to database, then call global static function
	HelpClasses.Context.InvalidateAllCache();
}


HelpClasses.Context:
public static void InvalidateAllCache()
{
	if ( System.Web.HttpContext.Current.Cache["RSSFEED123"] != null )
		System.Web.HttpContext.Current.Cache.Remove("RSSFEED123");
}


So inessence, when the administrator clicks the Save button we go to HelpClasses.Context.InvalidateAllCache() and it simply removes the item(s) from the cache.

I know I could maybe create a specialized cache dependency class derived from CacheDependency - but then the problem is that the GUI needs to communicate with it. I always take the easy way out, cause in the end it is all about delivering a working solution for the customer - not creating the most .NETed solution possible :)