Two Quick Tips on Sitecore.Caching
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
{
get
{
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