我有一个缓存一分钟的READONLY对象图,以便所有线程都可以使用它(下面的代码)。
public class ObjectGraphCache
{
static readonly Object storeLock = new object();
public ObjectGraph AllForElection(int ElectionId, System.Web.Caching.Cache cache)
{
string key=string.Format("AllForElection{0}",
ElectionId);
int timout = int.Parse(ConfigurationManager.AppSettings["dbCacheTimeInSeconds"]);
if (timout == 0)
{
ObjectGraph graph = new ObjectGraph();
graph.AllForElection(ElectionId);
return graph;
}
else
{
Object obj = cache[key];
if (obj == null)
{
lock (storeLock)
{
obj = cache[key]; // In case another page got the lock first and your are queued (Ensures only one get per cycle)
if (obj == null)
{
// Not in cache
ObjectGraph graph = new ObjectGraph();
graph.AllForElection(ElectionId);
cache.Insert(
key,
graph,
null,
DateTime.Now.Add(new TimeSpan(0, 0, timout)),
System.Web.Caching.Cache.NoSlidingExpiration);
return graph;
}
}
}
return (ObjectGraph)obj;
}
但是我想知道:为什么使用Cache对象,当我更容易将READONLY对象存储为静态时。这会存储一个指向堆的指针,因此在更新时,仍然处理前一个指针对象的线程将对旧对象进行一次罚款,并且在返回之前我也不必从缓存中转换对象。有人看到任何陷阱吗?
答案 0 :(得分:1)
将storeLock
放入应用程序变量