Improving performance using .Net Caching

.net caching

Found performance issues in a business class that I was using, in particular reading data.
A fair bit of the data being read was the same across multiple instances, so determined .net caching may make sense.

There is a built in .Net cache, that I was able to make use of within my class
Key sections of how to do this are below:

// Keep a static version of the cache, and initialize it to null
private static System.Web.Caching.Cache cache = null;

In the class init (or, at any point, before use), make sure it’s filled in:

// Note that even if you are running through ASP, the HttpContext.Current may NOT be populated, hence the HttpRuntime logic
if (null == cache)
    if (null == System.Web.HttpContext.Current)
        cache = System.Web.HttpRuntime.Cache;
        cache = System.Web.HttpContext.Current.Cache;

Then, to use:

<SOMETYPE> retval = null;
// Create a unique key, to see if it's already in there
string cachKey = string.Format("{0}:{1}",KeyValues, "<SOMETYPE>" );
retval = cache[cachKey] as <SOMETYPE>;
if (null == retval)
    // Load business object here, in slow-ish code
    retval = new <SOMETYPE>();
    if (null != retval)
        // Got a real value, add it to the cache
        //  This logic is to add with a 1 minute time span, so if it's not used within a minute, it will leave the cache.
        //  It may also leave based on memory constraints (Final parameter, for priority)
        cache.Add(cachKey, retval, null, DateTime.MaxValue, new TimeSpan(0, 1, 0), System.Web.Caching.CacheItemPriority.Normal, null);
Reference links, MSDN

Please Login to Comment.