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 - http://aspnet.4guysfromrolla.com/articles/100902-1.2.aspx - 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);
try
{
storedObject = (CacheObject)cache.Get(cacheKey);
}
catch (InvalidCastException)
{
cache.Remove(cacheKey);
}
if (storedObject == null)
{
DictionaryeventDictionary = 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:
- The InvalidCastException won't happen in real deployments - but does happen during recompiles in the development environment.
- 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