.NET ez 2013-01-25
當使用Cache常會發現,不知道何時要清除快取的窘境,太快清除就無法達到Cache效果,太慢又無法即時更新資訊! 本篇利用CacheDependency偵測檔案變更時,自動清除Cache,達到隨時都是最新資訊。
以下方式即可偵測檔案XXX.dat,如果檔案變更了,就會自動清除Cache:
CacheDependency CD = new CacheDependency(Server.MapPath("~/XXX.dat")); HttpRuntime.Cache.Add("cache key", "cache body", CD, DateTime.MaxValue, System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.High, null);
如果要釋放快取時呼叫指定Function,並且超過20秒未使用也會釋放,如下:
HttpRuntime.Cache.Add("cache key", "cache body", CD, DateTime.Now.AddSeconds(20), TimeSpan.Zero, CacheItemPriority.High, RemovedCallback);
public void RemovedCallback(String k, Object v, CacheItemRemovedReason r) { var key = k; var value = v; }
標籤: .NET
本文章網址:
https://www.ez2o.com/Blog/Post/csharp-HttpRuntime-Cache-CacheDependency
https://www.ez2o.com/Blog/Post/310
https://www.ez2o.com/Blog/Post/csharp-HttpRuntime-Cache-CacheDependency
https://www.ez2o.com/Blog/Post/310