.net MemoryCache - 关于删除项目的通知

时间:2014-04-08 11:39:00

标签: c# caching memorycache

我使用.net内存缓存与.NET 4.0和c#,我希望我的应用程序在删除项目时得到通知(所以我可以写它已被删除到日志文件或通知UI,该项目已被删除)。

无论如何都要这样做。

我使用的是System.Runtime.Caching.MemoryCache而不是System.Web.Caching

1 个答案:

答案 0 :(得分:13)

编辑:如果您使用System.Runtime.Caching.MemoryCacheCacheItemPolicy对象上有callback可供删除,还有一个用于更新。< / p>

myMemoryCache.Set("key", null, new CacheItemPolicy() {RemovedCallback = new CacheEntryRemovedCallback(CacheRemovedCallback) /* your other parameters here */});

public void CacheRemovedCallback(CacheEntryRemovedArguments arguments)
{
    // do what's needed
}

初步回答

System.Web.Caching命名空间为inserting data in the .net cache时,您可以选择将回调设置为通知删除

Cache.Insert("data", "", null, DateTime.Now.AddMinutes(1), System.Web.Caching.Cache.NoSlidingExpiration, CacheItemPriority.High, new CacheItemRemovedCallback(CacheRemovedCallback));

public string CacheRemovedCallback(String key, object value, System.Web.Caching.CacheItemRemovedReason removedReason)
{
    // here you can log, renew the value, etc...
}

还有Insert方法的签名,可让您将回调指定为notified before the item is removed