MemoryCache EvictionCallback 从未调用过

MemoryCache EvictionCallback never called

.Net核心内存缓存。我希望在从缓存中删除某个项目时收到通知。实施此示例后: https://docs.microsoft.com/en-us/aspnet/core/performance/caching/memory?view=aspnetcore-3.1

=> CreateCallbackEntry()。当我在

内放置一个断点时

驱逐回调:

private static void EvictionCallback(object key, object value,
    EvictionReason reason, object state)
{
    var message = $"Entry was evicted. Reason: {reason}.";
    // i should reach this after 10 seconds
}

只有在尝试再次读取刚刚存储在缓存中的相同密钥时才会命中断点。否则,即使网页保持打开状态,也永远不会调用驱逐方法。

控制器:

    public void OnGet()
    {
        _cache.GetOrCreate("key", item);

        // eviction callback does not fire until I query for the same key again below
        var t = _cache.GetOrCreate("key", item)
    }

缓存:

var cacheEntryOptions = new MemoryCacheEntryOptions()
    .SetAbsoluteExpiration(TimeSpan.FromSeconds(10))
    .RegisterPostEvictionCallback(callback: EvictionCallback, state: this);

cacheEntry = await createItem();
_cache.Set(key, cacheEntry, cacheEntryOptions);

PostEvicionCallback 不是过期事件。

The callback is executed when the cache entry is removed from the cache, not on expiration.

The removal of expired entries is done lazily after expiration upon an action on the cache. This is why the callback executed on your next request after expiration. For performance considerations we remove expired items in batches which has a minimum period specified by MemoryCacheOptions.ExpirationScanFrequency.

We do not currently expose any mechanism to notify exactly when cache entries expire but expired entries will eventually trigger the expiration callback some time in the future after any cache operation.

来自github.com/aspnet/Caching

您可以尝试降低 MemoryCacheOptions.ExpirationScanFrequency,但要注意性能影响。默认值为 1 分钟。