使用System.Web.Caching.Cache

时间:2011-07-22 14:43:16

标签: c# asp.net caching

我正在尝试使用缓存,但是会收到以下错误。如何正确使用缓存?

protected void Page_Load(object sender, EventArgs e) {
x = System.DateTime.Now.ToString();
 if (Cache["ModifiedOn"] == null) { // first time so no key/value in Cache
    Cache.Insert("ModifiedOn", x); // inserts the key/value pair "Modified On", x            
 }
 else { // Key/value pair already exists in the cache
     x = Cache["ModifiedOn"].ToString();
 } }
  

'System.Web.Caching.Cache'是'type',但用作'变量'

2 个答案:

答案 0 :(得分:43)

System.Web.Caching.Cache:这是.NET缓存的实现。

System.Web.HttpContext.Current.Cache:这是该实现的实例,它位于应用程序域中。

如果你不在aspx页面后面的代码中,我想你想使用第二个。如果您在aspx页面后面的代码中,请使用Cache。

您也可以直接使用Page.Cache.Insert通过页面对象引用System.Caching.Cache。所有这些都指向同一个应用程序缓存,它们对所有用户都是全局的。

答案 1 :(得分:0)

在新建或使用Init()方法初始化HttpContext时,该类存储HttpContext

然后使用HttpContext.Current.Cache

或者:使用参数currentcache创建用于读取和写入缓存的方法,并使用带有HttpContext.Current.Cache

调用它的示例代码对其进行记录