Two Quick Tips on Sitecore.Caching

Mon Dec 13 2010

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

Nick Wesselman

Nick Wesselman started working professionally in software development just a few days after everyone realized we dodged a bullet with the Y2k bug. He’s worked as a Sitecore solution partner, Technology partner, and now for Sitecore itself. He lives with his wife, son, and daughter in Asheville, NC.