【发布时间】: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
【问题讨论】: