Creating get from cache method using generic func delegate.

Download source code

Every time I used custom caching in my application I had to write a method, method will return cached version of the object if it’s available otherwise it will populate the cache and return the cached version.

While .net framework 2.0 allowed use of anonymous delegates it was bit cumbersome because we had to define an anonymous type delegate before using it, .net 3.5 introduces two pre-defined generic delegates Func and Action. You do not need to explicitly define a delegate any more. The difference between Func and Action is the return type. Func supports return type however Action supports methods with void return type. These delegates provide a set of pre-defined signatures that are ready to use.

Here’s the generic GetFromCache method which takes advantage of the generic delegate. Method takes two parameter cache name and function pointer, function pointer gets invoked when cache is not available. Method also uses singleton pattern to ensure that only other threads reading the data are waiting while cache is being repopulated.

public static readonly object getFromCacheLocker = new object();

public static TResult GetFromCache<TResult>(string cacheName
    ,Func<TResult> func){
    TResult rVal;

    if (HttpRuntime.Cache[cacheName] != null) {
        rVal = (TResult)HttpContext.Current.Cache[cacheName];
    } else {
        lock (getFromCacheLocker){
            if (HttpRuntime.Cache["cacheName"] != null){
                rVal = (TResult)HttpContext.Current.Cache[cacheName];
            }else{
                rVal = func();
                HttpContext.Current.Cache.Insert(cacheName, rVal);
            }
        }
    }


    return rVal;
}

Here’s how you will use this method.

List<Employee> empList = GetFromCache("myemployeename",delegate(){
return EmployeeManager.GetEmployees();
});

Bookmark with:
Technorati   Digg   Delicious   StumbleUpon   Facebook
My name is Jigar Desai I share my ideas on this site and you can contact me by filling contact form.