.NET 4 ObjectCache - 我们可以挂接到一个"缓存过期"事件? [英] .NET 4 ObjectCache - Can We Hook Into a "Cache Expired" Event?

查看:173
本文介绍了.NET 4 ObjectCache - 我们可以挂接到一个"缓存过期"事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的对象被缓存是这样的:

I've got a simple object being cached like this:

_myCache.Add(someKey, someObj, policy);



其中, _myCache 声明为 ObjectCache (但可通过DI注入为 MemoryCache.Default ), someObj中是我添加的对象,而政策 CacheItemPolicy

Where _myCache is declared as ObjectCache (but injected via DI as MemoryCache.Default), someObj is the object i'm adding, and policy is a CacheItemPolicy.

如果我有一个 CacheItemPolicy 是这样的:

If i have a CacheItemPolicy like this:

var policy = new CacheItemPolicy 
{ 
   Priority = CacheItemPriority.Default, 
   SlidingExpiration = TimeSpan.FromHours(1)
};



这意味着它会在1小时内到期。酷。

It means it will expire in 1 hour. Cool.

但什么会发生的是,在这一小时后倒霉的第一个用户将不得不等待的打击。

But what will happen is that unlucky first user after the hour will have to wait for the hit.

有什么办法,我可以挂接到一个过期事件/委托和手动刷新缓存?

Is there any way i can hook into an "expired" event/delegate and manually refresh the cache?

我看到有一提 CacheEntryChangeMonitor ,但无法找到如何利用它在我的例子任何meaninful DOCO /例子。

I see there is a mention of CacheEntryChangeMonitor but can't find any meaninful doco/examples on how to utilize it in my example.

PS。我知道我可以使用 CacheItemPriority.NotRemovable 并手动到期,但我不能这样做,在我目前的例子,因为缓存的数据是有点太复杂(比如我会需要像在我的代码10个不同的地方)为无效。

PS. I know i can use CacheItemPriority.NotRemovable and expire it manually, but i can't do that in my current example because the cached data is a bit too complicated (e.g i would need to "invalidate" in like 10 different places in my code).

任何想法?

推荐答案

有一个在 CacheItemPolicy 名为 RemovedCallback 这是一个类型的属性: CacheEntryRemovedCallback 。不知道为什么他们没有去标准事件的路线,但应该做你所需要的。

There's a property on the CacheItemPolicy called RemovedCallback which is of type: CacheEntryRemovedCallback. Not sure why they didn't go the standard event route, but that should do what you need.

http://msdn.microsoft.com/en-us/library/system.runtime.caching.cacheitempolicy.removedcallback.aspx

这篇关于.NET 4 ObjectCache - 我们可以挂接到一个"缓存过期"事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆