-
Caching Method Results in ASP.NET 2.0 using Delegates
-
Hmm. Talk about over-engineering. I don't think we really need generics at all, provided we're happy with a cast outside the method instead of inside it.
public delegate object MethodExecution();
public static object GetCachedMethod(string key, DateTime absoluteExpiration, MethodExecution method)
{
if (HttpContext.Current.Cache[key] == null)
HttpContext.Current.Cache.Insert(key,
method(),
null, absoluteExpiration, Cache.NoSlidingExpiration);
return HttpContext.Current.Cache[key];
}
...
return (DataSet)GetCachedMethod(key, DateTime.Now.AddDays(1),
delegate() { return SomeMethodThatReturnsADataSet(myParam); });
-
Caching Method Results in ASP.NET 2.0 using Generics & Delegates
-
Today I found myself coding a fairly familiar pattern - checking whether there was an entry in the ASP.NET cache with a particular key, if not, executing a method and adding the result to the cache, and either way, returning the result.
I wondered whether there was a "nice" way to do this using generics and anonymous delegates. This is what I came up with...public delegate T MethodExecution<T>();
public static T GetCachedMethod<T>(string key, DateTime absoluteExpiration, MethodExecution<T> method)
{
if (HttpContext.Current.Cache[key] == null)
HttpContext.Current.Cache.Insert(key,
method(),
null, absoluteExpiration, Cache.NoSlidingExpiration);
return (T)HttpContext.Current.Cache[key];
}
Now, to use this method, I could write the following to return a cached (by one day) result of the method SomeMethodThatReturnsADataSet.
return GetCachedMethod<DataSet>(key, DateTime.Now.AddDays(1),
delegate() { return SomeMethodThatReturnsADataSet(myParam); });I'm not sure whether this just makes things more obscure - any comments? :)