When inserting and retrieving items into cache. Is it best practice to perform a lock on the cache. I've following the guidelines from the following post.
What is the best way to lock cache in asp.net?
But i'm keen to get some context on whether i need to lock or not. This is the only location i use this cache.
private static object _tcsLock = new object();
public TcsService()
{
}
public LiveScoreTcs GetScoreCard()
{
// try to pull from cache here
var scorecard = HttpContext.Current.Cache[Global.Caching.SecondXILiveScoreKey];
if (scorecard != null)
{
return (LiveScoreTcs)scorecard;
}
lock (_tcsLock)
{
// cache was empty before we got the lock, check again inside the lock
scorecard = HttpContext.Current.Cache[Global.Caching.SecondXILiveScoreKey];
// cache is still empty, so retreive the value here
if (scorecard == null)
{
scorecard = BuildSecondXiLiveScorecard();
// store the value in the cache here
if (scorecard != null)
{
HttpContext.Current.Cache.Insert(Global.Caching.SecondXILiveScoreKey, scorecard,
null,
Global.Caching.AbsoluteExpiration.Tcs,
Cache.NoSlidingExpiration,
CacheItemPriority.Default,
null);
}
}
}
// return the cached value here
return (LiveScoreTcs)scorecard;
}