Two Quick Tips on Sitecore.Caching

Posted 12/13/2010 by techphoria414

Posted in

There are two "gotchas" in using Sitecore.Caching that have come back to bite me for the last time. I'm going to write about them so that I don't forget -- and hopefully help you out too.

1. If you don't want your Cache to be garbage collected, keep a static reference to it.

The Sitecore CacheManager uses WeakReference to store its caches. If you always retrieve your cache through Cache.GetNamedInstance, you may find that it disappears -- because it's been garbage collected! Keep a static reference to your cache, and use a locking object to ensure thread-safe creation of the Cache.

protected static Cache _cache = null ;
protected static Object _cacheLock = new Object ();

protected Cache Cache
        lock (_cacheLock)
            if (_cache == null )
                _cache =
Cache .GetNamedInstance(CACHE_NAME, Sitecore. StringUtil .ParseSizeString(_cacheMaxSize));
        return _cache;


2. When adding an item to your Cache with an absolute expiration, always use DateTime.UtcNow as your base time

Otherwise (at least in U.S. time zones) you will find your item has already expired as soon as you attempt to access it. Oops.

Cache.Add(object.ID, object, object.Length, DateTime .UtcNow.AddMinutes(_cacheExpirationMinutes));


Happy Sitecoring,

- Nick / techphoria414


Pre-Disqus Comments

  • Jonathan Falkner's gravatar Jonathan Falkner said:
    9/27/2013 4:24 PM

    Thank you so much for posting this online. You saved me hours of research!

  • Mark Ursino's gravatar Mark Ursino said:
    2/15/2013 9:45 AM

    Thanks for the tips Nick, this is very useful. I saw how the cache is used in the custom WeBlog dictionary implementation so this is some great content.

Sitecore MVP

Popular Posts