【发布时间】:2015-08-24 14:15:14
【问题描述】:
在缓存中插入和检索项目时。对缓存执行锁定是最佳实践吗?我已遵循以下帖子中的指南。
What is the best way to lock cache in asp.net?
但我很想了解我是否需要锁定。这是我使用此缓存的唯一位置。
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;
}
【问题讨论】:
-
_tcsLock在哪里声明和/或初始化? -
刚刚更新..谢谢
-
请注意
Cache在多线程环境中会出现任何共享状态的所有正常问题。最重要的是,可能有一些特定于Cache的问题,但“用例是什么”的答案是“所有正常用例,可能还有一些Cache特定用例”。