Monday, December 15, 2008

ASP.Net Cacheing - Excellent :)

I've spent the weekend writing some code which consumes a web service and uses it populate a table and a chart.

The problem is that talking to the webservice is quite slow (a good chunk of a second for the web hit) - but the good news is that the results don't change much from hour to hour - so the results are a really good candidate for cacheing.

I looked around and discovered this article from 4guysfromrolla - - and saw how really lovely the ASP.Net cacheing is.

Here's the code I wrote....

private static CacheObject GetCachedObjectForEvent(string eventName, Cache cache)
CacheObject storedObject = null;

string cacheKey = string.Format("MY_EVENT_{0}", eventName);
storedObject = (CacheObject)cache.Get(cacheKey);
catch (InvalidCastException)

if (storedObject == null)
Dictionary eventDictionary = HttpCollector.Collect(eventName);
storedObject = new CacheObject(eventDictionary);
cache.Add(cacheKey, storedObject, null, DateTime.Now.AddMinutes(60.0), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.Normal, null);
return storedObject;

A couple of things to note here:
  1. The InvalidCastException won't happen in real deployments - but does happen during recompiles in the development environment.
  2. The cached object here is only stored for at most 60 minutes from insertion - an alternate strategy might have been to store it on a sliding scale.

No comments:

Post a Comment