【问题标题】:Does ASP.NET Cached Objects update automatically with the object updating?ASP.NET 缓存对象是否会随着对象的更新而自动更新?
【发布时间】:2010-07-03 05:45:40
【问题描述】:

我在网上找到了一些代码,这让我很反感。看看下面的代码。只有当 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

【问题讨论】:

    标签: c# asp.net caching


    【解决方案1】:

    无论命中是什么,此代码都会更新缓存的对象。重要的一行在这里:

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

    它在缓存中获取对HitInfo 对象的引用,除非它不存在,在这种情况下它会创建一个新对象。所以 ASP.Net 缓存和局部变量 hit 都引用了同一个对象——在这段代码中更新它就是在缓存中更新它。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-01
      • 2020-11-22
      • 2011-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-15
      相关资源
      最近更新 更多