缓存== null?可能吗?

时间:2011-04-06 08:38:42

标签: c# .net asp.net asp.net-cache

发表以下声明是否合法:

if(Cache[CACHE_KEY] == null)
{
    //do something to form cache
}
else
{
    //do something else that uses cache
}

我不确定我的程序是否实际运行正常(即使它编译)并且我想知道缓存是否不存在它是否设置为null?

4 个答案:

答案 0 :(得分:6)

是的,这是合法的(但标题中的问题不是,详见下文)。

尽管如此,检查缓存中的类型是否是您期望的类型而不是必须进行两次检查可能是明智的,例如:

//in English, the following line of code might read:
//    if the item known in the cache by the specified key is in
//    in fact of type MyExpectedReferenceType, then give me it 
//    as such otherwise, give me a null reference instead...
var myCachedInstance = Cache[key] as MyExpectedReferenceType;
if (myCachedInstance == null)
{  
    //we retrieved a reference to an instance of an MyExpectedReferenceType
}
else
{
    //oh, no - we didn't!
}

虽然重新阅读你的问题,并且考虑到你的计划无法正常运作,但我很想说你有比这更大的问题; 你的程序无法正常工作? Cache实例本身在访问时永远不会是null - 它是Page的只读字段。但是,您预期的缓存值可能是null,如果这是问题,您应该收到NullReferenceException - 是这样吗?

更新:

要解决您的评论,请查看我添加到代码中的评论。

答案 1 :(得分:2)

非常合法;而不是在执行操作之前更好地检查值,尤其是确保密钥没有滑出或过期等。

答案 2 :(得分:2)

您发布的代码中存在潜在的竞争条件:

if(Cache[CACHE_KEY] == null) 
{     
    //do something to form cache 
} 
else 
{     
    // Another thread could have removed CACHE_KEY from the Cache before you get here

}

最好首先从缓存中提取对象,然后将其测试为null,例如:

MyObject cachedObject = Cache[CACHE_KEY] as MyObject;
// or MyObject cachedObject = (MyObject) Cache[CACHE_KEY]; if you know it is of type MyObject
if(cachedObject == null) 
{     
    cachedObject = ... // generate the cached object
    Cache.Insert(CACHE_KEY, cachedObject, ...);
} 

// use cachedObject

答案 3 :(得分:0)

是的,可能,Cache将始终初始化(如会话和应用程序obj) 但是您可以检查缓存中的密钥是否为空