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