HttpRuntime.Cache
和HttpContext.Current.Cache
有何区别?
HttpRuntime.Cache
和HttpContext.Current.Cache
有何区别?
在缓存方面,我研究了使用HttpContext.Current.Cache,但在阅读了其他博客之后,我发现使用HttpContext进行缓存实际上是使用HttpRuntime.Cache来执行缓存的。直接使用HttpRuntime的优点是它始终可用,例如在控制台应用程序和单元测试中。
使用HttpRuntime.Cache很简单。对象可以存储在缓存中,并由字符串索引。除了键和要缓存的对象之外,另一个重要参数是过期时间。该参数设置对象在从缓存中删除之前停留在缓存中的时间。
使用HttpContext进行缓存是利用HttpRuntime.Cache进行实际缓存。直接使用HttpRuntime的优点是在控制台应用程序和单元测试中始终可用。
HttpRuntime.Cache
比 HttpContext.Current.Cache
更简单。如已经提到的,对象可以存储在缓存中,并由字符串索引。同时,在单元测试和控制台HttpRuntime
也可用。HttpRuntime.Cache
的示例。public static XmlDocument GetStuff(string sKey)
{
XmlDocument xmlCodes;
xmlCodes = (XmlDocument) HttpRuntime.Cache.Get( sKey );
if (xmlCodes == null)
{
xmlCodes = SqlHelper.ExecuteXml(new dn("Nodes", "Node"), "Get_Stuff_From_Database", sKey);
HttpRuntime.Cache.Add(sKey, xmlCodes, null,
DateTime.UtcNow.AddMinutes(1.0),
System.Web.Caching.Cache.NoSlidingExpiration,
System.Web.Caching.CacheItemPriority.Normal, null);
}
return xmlCodes;
}
GetStuff
方法需要一个字符串参数,用于从数据库中检索一组项目。该方法首先检查缓存中是否存在由参数键索引的XmlDocument
。如果存在,则简单地返回此对象;否则,它会查询数据库。在从数据库检索到文档后,它将其放入缓存中。如果在规定时间内再次调用此方法,则会获取对象而不是访问数据库。