Smart or Silly?
I find that I constantly have to write code to first check for an item in the ASP.NET cache and if it is not found then create the item for the first time and insert it into the cache for subsequent look-ups. I began to wonder if I could simplify that process and came up with the following code:
public delegate object Create(); public static T GetOrCreate(string key, Create create) { Cache cache = HttpRuntime.Cache; object value = cache[key]; // If there is no object in the cache run the create delegate if (value == null && create != null) { value = create(); if (value != null) cache.Insert(key, value); } // Cast the return object return value == null ? default(T) : (T)value; }
You could then make a single call to either get the item in cache or create it for the first time like this:
DataSet ds = GetOrCreate<DataSet>("users", delegate() { DataSet ds = new DataSet(); // Get data from database... return ds; });
Using an anonymous delegate the syntax is pretty easy to either get the item if it’s already cached or create it for the first time. It has the added benefit of placing the code that creates the cache item right next to the code that gets it from the cache to make comprehending the code easier for other developers.
So my question is, is this a clever approach to an old problem, or am I going overboard?