14

我正在使用带有 .NET 4.0 和 c# 的 .net 内存缓存,我希望在删除项目时通知我的应用程序(因此我可以将其写入日志文件或通知 UI,该项目已移除)。

有没有办法做到这一点。

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

4

1 回答 1

21

编辑:如果您使用的是对象上System.Runtime.Caching.MemoryCache有一个用于删除的回调CacheItemPolicy,以及一个用于更新的回调。

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

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

初步答案

在命名空间的 .net 缓存中插入数据时,System.Web.Caching您可以选择设置回调以通知删除

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,可让您指定在删除项目之前要通知的回调

于 2014-04-08T11:43:32.887 回答