Why is caching important?

Caching is important because it can speed up your website or application. Why spend time and resources by needless calls to the database each time a user visits a page or uses an app?

Here is an example for you to read and use yourself.

using System;
using System.Runtime.Caching;
namespace CodeShare.Web.App_Code.Helpers
{
    public static class Caching
    {
        /// <summary>
        /// A generic method for getting and setting objects to the memory cache.
        /// </summary>
        /// <typeparam name="T">The type of the object to be returned.</typeparam>
        /// <param name="cacheItemName">The name to be used when storing this object in the cache.</param>
        /// <param name="cacheTimeInMinutes">How long to cache this object for.</param>
        /// <param name="objectSettingFunction">A parameterless function to call if the object isn't in the cache and you need to set it.</param>
        /// <returns>An object of the type you asked for</returns>
        public static T GetObjectFromCache<T>(string cacheItemName, int cacheTimeInMinutes, Func<T> objectSettingFunction)
        {
            ObjectCache cache = MemoryCache.Default;
            var cachedObject = (T)cache[cacheItemName];
            if (cachedObject == null)
            {
                CacheItemPolicy policy = new CacheItemPolicy();
                policy.AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(cacheTimeInMinutes);
                cachedObject = objectSettingFunction();
                cache.Set(cacheItemName, cachedObject, policy);
            }
            return cachedObject;
        }
    }
}

Usage

int resultOfExpensiveQuery = GetObjectFromCache<int>("resultOfExpensiveQuery", 10, CallSlowQueryFromDatabase);

Parameters

The above code accepts 3 parameters. The first one is the name. When storing an object in the cache, it uses a name, so you can call it later or replace it later.

The next parameter is the cache time in minutes. This tells the application how long to store the object in the cache for.

The last parameter is the clever part. This is a delegate function. This gets called if the object isn't in the cache so the object can be set and stored in the cache. You can change this delegate function to accept parameters into it.

Generic method

The last thing to note is the use of T in the angled brackets and inside the method. This makes it a generic method. When you call the method you can tell it what Type T is.
It will return your cached object back in the form of whatever you specified T as.

A good use for this code would be the site navigation. There is no point recreating it for every page view or every user.

Real world example

To see an example of this code being used, have a look at my site navigation model post.

Want to thank me?

If I've helped you out and you want to thank me, why not buy me a coffee?

About the author

Paul Seal

Umbraco MVP and .NET Web Developer from Derby (UK) who specialises in building Content Management System (CMS) websites using MVC with Umbraco as a framework. Paul is passionate about web development and programming as a whole. Apart from when he's with his wife and son, if he's not writing code, he's thinking about it or listening to a podcast about it.

Related Posts

How to solve the error "Could not load file or assembly 'Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.0.0 ..."

This post will show you how to solve the error "Could not load file or assembly 'Microsoft.CodeDom.P…

Read Post

Cyber Monday Deals

As it is Cyber Monday and you are probably looking for some tech related deals, I thought I would cr…

Read Post

How to use Donut Caching in Umbraco and MVC

In this post I show you how easy Donut Caching is to use in Umbraco and MVC. It's very clever and no…

Read Post

6 winning tips to launch a successful YouTube channel

In this post I give you 6 tips to launch a successful YouTube channel.

Read Post