2011-08-22 46 views
1

我想在ASP.NET缓存中放置一个项目,比如说一个数据集,并且根本不会过期,直到我的应用程序中发生需要该项目的事件被刷新。但在此之前,它不应该过期。手动/立即过期缓存项目

所以a)是否可以设置永不过期的缓存项目(除了将来设置过期1年之外),以及b)如何手动强制项目过期?

谢谢!

回答

1

我在想这会适合你。然后,当你准备要刷新的项目,你删除它手动形成缓存,并重新设置它...

Page.Cache.Add("object", 
      "something", 
      null, 
      System.Web.Caching.Cache.NoAbsoluteExpiration, 
      System.Web.Caching.Cache.NoSlidingExpiration, 
      CacheItemPriority.NotRemovable, 
      new CacheItemRemovedCallback((s, o, r) => 
      { 
       // some callback code if you want... 
      })); 

修订(更好的演示):

当然
private int _counter = 0; 

    protected void Page_Load(object sender, EventArgs e) 
    { 
     // You can add the cache key like this 
     AddToCache("key",() => "some object " + _counter++); 

     //Any time you want to refresh the value, you can call RefreshCachedValue 
     RefreshCachedValue("key"); 
     RefreshCachedValue("key"); 
     RefreshCachedValue("key"); 
     RefreshCachedValue("key"); 
     RefreshCachedValue("key"); 
     // In this demo, the cached value is now "some object 5" 
    } 

    private void AddToCache(string key, Func<object> getValueFunction) 
    { 
     Page.Cache.Add(key, 
      getValueFunction(), 
      null, 
      System.Web.Caching.Cache.NoAbsoluteExpiration, 
      System.Web.Caching.Cache.NoSlidingExpiration, 
      CacheItemPriority.NotRemovable, 
      new CacheItemRemovedCallback((s, o, r) => 
      { 
       AddToCache(s, getValueFunction); 
      })); 
    } 

    private void RefreshCachedValue(string key) 
    { 
     Page.Cache.Remove(key); 
    } 
+0

辉煌,感谢所有。需要了解回调了。 :) –

1

是有可能从未设置缓存项到期(距到期设置说1年以后)

排序

- 该Insert方法有超载,支持:(reference

DataSet myDataSet = getDataSet(); 

Page.Cache.Insert("MyDataSetCacheKey", myDataSet) 

这会将对象添加到高速缓存中,但没有滑动到期并且没有绝对过期,但它使用默认优先级,而不是NotRemovable。如果您想强制执行此操作,则必须自己为Insert编写扩展方法。

如何手动强制项目过期?

我假设你的意思是'我已经永久缓存了这些数据,但现在我想改变它'。在这种情况下,你会不会过期的,你只是从缓存中删除:

Page.Cache.Remove("MyDataSetCacheKey") 

在逻辑上,有从缓存中删除,因为它已过期的项目没有什么区别,是由服务器刷新试图清除内存或手动删除内存。

+0

啊。 。删除:<=>失效! *拍头* –