c# - 如何将侦听器附加到在密钥到期时调用的 MemoryCache?
问题描述
我MemoryCache
在我的一个项目中使用缓存一些键和值。
private bool CacheEntries<T>(MemoryCache memoryCache, string cacheKey, T value, Configuration config, Action<MemoryCacheEntryOptions> otherOptions = null)
{
int minutes = randomGenerator.Next(config.LowTime, config.HighTime);
MemoryCacheEntryOptions options = new MemoryCacheEntryOptions()
{
Size = config.Size,
Priority = config.Priority,
AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(minutes)
};
if (otherOptions != null) otherOptions(options);
CacheKeys.Add(cacheKey);
memoryCache.Set<T>(cacheKey, value, options);
return true;
}
如上所示,我的密钥已过期。此外,我将相同的密钥存储在CacheKeys
HashSet
数据结构中以供以后使用。有什么方法可以在我MemoryCache
的任何项目到期时附加一个监听器,那么应该调用该监听器,以便我也可以从中删除这些键CacheKeys
HashSet
。基本上我想与我在CacheKeys
and中的内容保持一致MemoryCache
。
这可能吗?
解决方案
您似乎正在使用 Microsoft.Extensions.Caching.Memory 中的 Platform Extensions 对象。当您在缓存中设置项目的值时,您可以使用MemoryCacheEntryOptions.PostEvictionCallbacks
MemoryCacheEntryOptions 对象的属性:
获取或设置将在缓存条目从缓存中逐出后触发的回调。
或者,如果您可以更改为 System.Runtime.Caching 版本MemoryCache
,则可以CacheItemPolicy
在设置值时使用 。从文档中:
CacheItemPolicy 实例包含可以与缓存条目相关联的信息。例如,当即将从缓存中删除缓存条目时,会将 CacheEntryUpdateArguments 对象传递给回调方法。CacheEntryUpdateArguments 对象的 UpdatedCacheItemPolicy 属性可以传递对 CacheItemPolicy 实例的引用,该实例可以包括有关缓存条目的逐出和到期详细信息。
该版本的另一种选择MemoryCache
是调用CreateCacheEntryChangeMonitor
:
CreateCacheEntryChangeMonitor 方法创建一个 CacheEntryChangeMonitor 实例。此专用更改监视器用于监视键集合中指定的缓存条目,并在条目更改时触发事件。
由于以下任何原因,受监控的条目被视为已更改:
在调用 CreateCacheEntryChangeMonitor 方法时,该键不存在。在这种情况下,生成的 CacheEntryChangeMonitor 实例会立即设置为更改状态。这意味着当代码随后绑定更改通知回调时,会立即触发回调。
关联的缓存条目已从缓存中删除。如果条目被显式删除、过期或被逐出以恢复内存,则可能会发生这种情况
推荐阅读
- javascript - 循环遍历构造函数中的类键?
- ms-access - 可以在查询 SQL 语句中传递变量吗?
- character-encoding - 连接和 Python 中的编码不匹配
- r - 重叠的时期,通过 R 的 ID 对活动进行分组
- image - 如何用图像填充整个框架?
- python - 如何重构此递归策略表达式 Strategy 以参数化其长度?
- powershell - Powershell将进程的pid添加到FileVersionInfo
- php - How to insert href link in this button tag
- python - Python Regex: AttributeError: 'str' object has no attribute 'Match'
- javascript - 创建递归表单元素