代码之家  ›  专栏  ›  技术社区  ›  SpoiledTechie.com

ASP.NET缓存对象是否随对象更新而自动更新?

  •  3
  • SpoiledTechie.com  · 技术社区  · 15 年前

    我在网上找到了一些代码,它把我甩了。请看下面的代码。只有当hits==1时,才会注意到缓存是否被添加。之后,不会更新缓存对象。它回避了一个问题,对象在更新时是否也自动更新缓存?这里的答案将使我在一些类中删除一些代码。

    public static bool IsValid( ActionTypeEnum actionType )
    {
       HttpContext context = HttpContext.Current;
       if( context.Request.Browser.Crawler ) return false;
    
       string key = actionType.ToString() + context.Request.UserHostAddress;
       var hit = (HitInfo)(context.Cache[key] ?? new HitInfo());
    
       if( hit.Hits > (int)actionType ) return false;
       else hit.Hits ++;
    
       if( hit.Hits == 1 )
          context.Cache.Add(key, hit, null, DateTime.Now.AddMinutes(DURATION), 
             System.Web.Caching.Cache.NoSlidingExpiration, 
             System.Web.Caching.CacheItemPriority.Normal, null);
       return true;
    }
    

    我想我只需要在if语句后添加行:

     if( hit.Hits == 1 )
                  context.Cache.Add(key, hit, null, DateTime.Now.AddMinutes(10), 
                     System.Web.Caching.Cache.NoSlidingExpiration, 
                     System.Web.Caching.CacheItemPriority.Normal, null);
        else if (hit.Hits > 1)
    {context.Cache.Remove(key);             
     context.Cache.Add(key, hit, null, DateTime.Now.AddMinutes(10), 
                     System.Web.Caching.Cache.NoSlidingExpiration, 
                     System.Web.Caching.CacheItemPriority.Normal, null);
    }
    

    在下面的页面找到代码: http://www.codeproject.com/KB/aspnet/10ASPNetPerformance.aspx?msg=2809164

    1 回复  |  直到 15 年前
        1
  •  2
  •   womp    15 年前

    此代码正在更新缓存对象,而不管命中率是多少。重要的一行是:

    var hit = (HitInfo)(context.Cache[key] ?? new HitInfo());
    

    它正在获取一个参考 HitInfo 对象在缓存中,除非它不存在,在这种情况下,它将创建一个新的对象。所以ASP.NET缓存和本地变量 hit 有一个对同一个对象的引用-在这段代码中更新它就是在缓存中更新它。

    在创建新的代码的情况下,它会将其添加到缓存中,因此下次代码执行时,上面的行将返回该对象。不需要删除对象然后重新缓存它。