ASP.NET Software Engineering

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)
            null, absoluteExpiration, Cache.NoSlidingExpiration);

    return HttpContext.Current.Cache[key];
return (DataSet)GetCachedMethod(key, DateTime.Now.AddDays(1),
                delegate() { return SomeMethodThatReturnsADataSet(myParam); });

5 replies on “Caching Method Results in ASP.NET 2.0 using Delegates”

You don”t need generics if you”re happy with using code that has race conditions in it. Think about what will happen if the caching engine decides to drop your object between the line that inserts it and the one that retrieves it. Anything you insert is not guaranteed to stay cached until it expires, only not to stay longer.

The correct way:

object value = HttpContext.Current.Cache[key];

if( value == null ) {

value = method();

HttpContext.Current.Cache.Insert(key, value, …);


return value;

Not really, there would be if we used Cache.Add instead of Cache.Insert. Insert will replace an existing key, if it manages to get inserted multiple times. You could lock the code around the check and insertion but that would be an unneeded bottleneck and imo it”s better to just evaluate the method multiple times.

Hey, just a comment, appreciate you sharing your thoughts:

>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.

I just want to say that the whole reason i use generics is to ensure that people aren”t making casts outside the methods.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.