c# - ASP.NET 缓存对象是否会随着对象更新自动更新?

标签 c# asp.net caching

我在网上找到了一些代码,这让我很吃惊。看看下面的代码。您会注意到只有当 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

最佳答案

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

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

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

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

关于c# - ASP.NET 缓存对象是否会随着对象更新自动更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3169260/

相关文章:

c# - 将 IQueryable 转换为 IOrderedQueryable

c# - 重新计算单元格值的 Excel C# 事件

c# - jQuery/ajax POST 一个数组/对象到后面的 C# 代码

caching - 如何为 Gitlab Pages 启用 GZip 压缩?

linux - 如何设置一个简单的本地 linux 代理来缓存所有 HTTP 请求以供离线浏览

java - cpu缓存和内存缓存有什么区别

c# - 如何在 sandcaSTLe xml 文档构建中排除不可浏览的成员

c# - System.Collections.Generic.KeyNotFoundException Dynamics CRM C# 查找字段错误

c# - 在 C# 中创建自定义绑定(bind)

javascript - 使用javascript下载文件弹出框