System.Web.Caching.Cache在模型中引发空异常 [英] System.Web.Caching.Cache throws null exception in a model

查看:219
本文介绍了System.Web.Caching.Cache在模型中引发空异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也许这个问题应该很容易,但事实并非如此.我已阅读使用System.Web的问题. ASP.NET中的Caching.Cache类.

Maybe this question should be easy, but it is not. I have read Problem Using the System.Web.Caching.Cache Class in ASP.NET.

我有一个单例课程:

private System.Web.Caching.Cache _cache;
private static CacheModel _instance = null;

private CacheModel() {
   _cache = new Cache();
}

public static CacheModel Instance {
         get {
            return _instance ?? new CacheModel();
         }
      }

public void SetCache(string key, object value){
   _cache.Insert(key, value);
}

如果在代码中的其他任何地方,我都会调用以下代码:

If, anywhere else in my code, I call the following:

CacheModel aCache = CacheModel.Instance;
aCache.SetCache("mykey", new string[2]{"Val1", "Val2"});  //this line throws null exception

为什么第二行抛出空引用异常?

Why does the second line throw a null reference exception?

也许我在代码中的某个地方犯了一些错误?

Maybe I have made some mistake somewhere in the code?

谢谢.

推荐答案

您不应使用Cache类型的

此API支持.NET Framework基础结构,不能直接在您的代码中使用.

This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.

如果不直接查看为什么,您将得到null引用异常,而我之前曾遇到过此问题,这是

Without looking directly into why you would get a null reference exception, and I've ran into this problem before, this is tied in with the infrastructure and lifecycle of a web application:

在每个应用程序域中创建一个此类的实例,并且只要该应用程序域保持活动状态,它就一直有效.有关此类实例的信息,可以通过HttpContext对象的Cache属性或Page对象的Cache属性获得.

One instance of this class is created per application domain, and it remains valid as long as the application domain remains active. Information about an instance of this class is available through the Cache property of the HttpContext object or the Cache property of the Page object.

最重要的是,不要以这种方式直接使用System.Web.Caching.Cache类型-访问现有的缓存实例或使用诸如

Bottom line, don't use the System.Web.Caching.Cache type directly in this way - either access an existent cache instance or use an alternative like the Caching Application Block of the Enterprise Library.

这篇关于System.Web.Caching.Cache在模型中引发空异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆