【问题标题】:How to attach a listener to MemoryCache which gets called on expiration of keys?如何将侦听器附加到在密钥到期时调用的 MemoryCache?
【发布时间】:2020-10-11 20:23:06
【问题描述】:

我在我的一个项目中使用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 上附加一个侦听器,只要它使任何项目到期,就应该调用该侦听器,以便我也可以从CacheKeysHashSet 中删除这些键。基本上我想与CacheKeysMemoryCache 中的内容保持一致。

这可能吗?

【问题讨论】:

    标签: c# memorycache


    【解决方案1】:

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

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

    或者,如果您可以更改为MemoryCache 的System.Runtime.Caching 版本,则可以在设置值时使用CacheItemPolicy。来自the documentation

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

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

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

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-01
      • 2014-12-01
      • 2012-11-11
      • 1970-01-01
      • 2016-03-26
      • 2016-03-25
      • 2020-11-14
      • 2013-01-27
      相关资源
      最近更新 更多