【问题标题】:Cache == null? Is it possible?缓存 == 空?是否可以?
【发布时间】:2011-04-06 08:38:41
【问题描述】:

作出以下声明是否合法:

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

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

【问题讨论】:

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


    【解决方案1】:

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

    不过,检查缓存中的类型是否符合您的预期可能是明智之举,而不必进行两次检查,例如:

    //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 - 是这样吗?

    更新:

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

    【讨论】:

    • 对不起,“Cache[key] as MyExpectedReferenceType”是做什么的?
    • 哈哈,它实际上比我想的要简单得多。我要做的就是弄清楚缓存是否存在,如果确实存在,请使用它...
    【解决方案2】:

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

    【讨论】:

    • 根本不检查要好;或比认为它包含有效值更好。
    【解决方案3】:

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

    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
    
    }
    

    最好先从缓存中提取对象,然后测试它是否为空,例如:

    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
    

    【讨论】:

      【解决方案4】:

      是的,有可能,缓存将始终被初始化(如会话和应用程序 obj) 但是你可以检查缓存中的某个键是否为空

      【讨论】:

        猜你喜欢
        • 2011-12-10
        • 1970-01-01
        • 1970-01-01
        • 2015-12-22
        • 1970-01-01
        • 2010-12-31
        • 2011-07-08
        • 2023-03-22
        • 2019-11-14
        相关资源
        最近更新 更多