小心!!,使用缓存的陷阱

 为了提高系统性能,缓存是必不可少的,但是一不小心,就会出现null。
例如情况下面的情况:一个website有一个default.aspx页面,在页面Page_Load事件里,我往缓存myname里存入数据,如下:
 protected void Page_Load(object sender, EventArgs e)
    {
       
        
if (!Page.IsPostBack)
        {
            HttpContext ctx 
= HttpContext.Current;
            ctx.Cache.Insert(
"myname""dream"null, DateTime.Now.AddHours(1), TimeSpan.Zero);
        }

    }

然后在页面防止一个button,在button事件里读取缓存,你很容易写成如下代码:
 protected void Button1_Click(object sender, EventArgs e)
    {
        HttpContext ctx 
= HttpContext.Current;
     
if(ctx.Cache["myname"!= null)
      {
          Response.Write((
string)ctx.Cache["mynamn"]);          
      }
      
else
      {       
        ctx.Cache.Insert(
"myname","dream",null,DateTime.Now.AddHours(1), TimeSpan.Zero);
        Response.Write((
string)ctx.Cache["myname"]); 
         
     } 
}

然而,当你运行时,你会发现类似这样的代码并不能够取到缓存里的值,正确的方法应该是:
 protected void Button1_Click(object sender, EventArgs e)
    {
        
        HttpContext ctx 
= HttpContext.Current;
        
string name = Cache["myname"as string;

        
if (name != null)
        {
            Response.Write(name);
        }
        
else
        {
            ctx.Cache.Insert(
"myname""dream"null, DateTime.Now.AddHours(1), TimeSpan.Zero);
            Response.Write(name);
        }
 
    }

这个方法和上面方法唯一一个区别,就是把缓存放到一个局部变量里,通过判断局部变量而不是缓存看其是否为空。
原文地址:https://www.cnblogs.com/mqingqing123/p/940221.html