首页 > 解决方案 > 如何将侦听器附加到在密钥到期时调用的 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。基本上我想与我在CacheKeysand中的内容保持一致MemoryCache

这可能吗?

标签: c#memorycache

解决方案


您似乎正在使用 Microsoft.Extensions.Caching.Memory 中的 Platform Extensions 对象。当您在缓存中设置项目的值时,您可以使用MemoryCacheEntryOptions.PostEvictionCallbacksMemoryCacheEntryOptions 对象的属性:

获取或设置将在缓存条目从缓存中逐出后触发的回调。

或者,如果您可以更改为 System.Runtime.Caching 版本MemoryCache,则可以CacheItemPolicy在设置值时使用 。从文档中

CacheItemPolicy 实例包含可以与缓存条目相关联的信息。例如,当即将从缓存中删除缓存条目时,会将 CacheEntryUpdateArguments 对象传递给回调方法。CacheEntryUpdateArguments 对象的 UpdatedCacheItemPolicy 属性可以传递对 CacheItemPolicy 实例的引用,该实例可以包括有关缓存条目的逐出和到期详细信息。

该版本的另一种选择MemoryCache是调用CreateCacheEntryChangeMonitor

CreateCacheEntryChangeMonitor 方法创建一个 CacheEntryChangeMonitor 实例。此专用更改监视器用于监视键集合中指定的缓存条目,并在条目更改时触发事件。

由于以下任何原因,受监控的条目被视为已更改:

  • 在调用 CreateCacheEntryChangeMonitor 方法时,该键不存在。在这种情况下,生成的 CacheEntryChangeMonitor 实例会立即设置为更改状态。这意味着当代码随后绑定更改通知回调时,会立即触发回调。

  • 关联的缓存条目已从缓存中删除。如果条目被显式删除、过期或被逐出以恢复内存,则可能会发生这种情况


推荐阅读