HttpRuntime.Cache和HttpContext.Current.Cache之间的区别是什么?

66

HttpRuntime.CacheHttpContext.Current.Cache有何区别?

3个回答

64
我从 http://theengineroom.provoke.co.nz/archive/2007/04/27/caching-using-httpruntime-cache.aspx 中了解到以下细节:

在缓存方面,我研究了使用HttpContext.Current.Cache,但在阅读了其他博客之后,我发现使用HttpContext进行缓存实际上是使用HttpRuntime.Cache来执行缓存的。直接使用HttpRuntime的优点是它始终可用,例如在控制台应用程序和单元测试中。

使用HttpRuntime.Cache很简单。对象可以存储在缓存中,并由字符串索引。除了键和要缓存的对象之外,另一个重要参数是过期时间。该参数设置对象在从缓存中删除之前停留在缓存中的时间。

这里有一个好链接。

另一个好资源。


pjohnson页面已经迁移到http://weblogs.asp.net/pjohnson/httpruntime-cache-vs-httpcontext-current-cache。重定向无效,花了一段时间才在wayback机器上找到它。 - goodeye

19

使用HttpContext进行缓存是利用HttpRuntime.Cache进行实际缓存。直接使用HttpRuntime的优点是在控制台应用程序和单元测试中始终可用。


1
使用 HttpRuntime.CacheHttpContext.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。如果存在,则简单地返回此对象;否则,它会查询数据库。在从数据库检索到文档后,它将其放入缓存中。如果在规定时间内再次调用此方法,则会获取对象而不是访问数据库。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接