.Net Core MemoryCache PostEvictionCallback 无法正常工作

标签 .net caching asp.net-core memorycache

我已在 Microsoft.Extensions.Caching.Memory.MemoryCache 中设置了可滑动过期的缓存项。 我想在每次缓存项过期时触发回调,但是直到我查询缓存中是否有过期的缓存项时才会触发回调。

这是代码:

using System;
using Microsoft.Extensions.Caching.Memory;

namespace Memcache
{
    public class Program
    {
        private static MemoryCache _cache;
        private static int _cacheExpSecs;

        public static void Main(string[] args)
        {
            _cache = new MemoryCache(new MemoryCacheOptions());
            _cacheExpSecs = 2;

            var cacheEntryOptions = new MemoryCacheEntryOptions()
            .SetSlidingExpiration(TimeSpan.FromSeconds(_cacheExpSecs))
            .RegisterPostEvictionCallback(callback: EvictionCallback);

            _cache.Set(1, "One", cacheEntryOptions);
            _cache.Set(2, "Two", cacheEntryOptions);

            var autoEvent = new System.Threading.AutoResetEvent(false);

            System.Threading.Timer timer = new System.Threading.Timer(checkCache, autoEvent, 1000, 6000);

            Console.Read();
        }

        private static void checkCache(Object o)
        {
            if(_cache.Get(1)!=null)
            {
                Console.WriteLine(string.Format(@"checkCache: Cache with key {0} will be removed manually and will trigger the callback.", 1));
                _cache.Remove(1);
            }
            else
            {
                Console.WriteLine(string.Format("checkCache: Cache with key {0} is expired.", 1));
            }


            if(_cache.Get(2) != null)
            {
                Console.WriteLine(string.Format("checkCache: Cache with key {0} will expire in {1} seconds, but won't trigger the callback until we check it's value again.", 2, _cacheExpSecs));
            }
            else
            {
                Console.WriteLine(string.Format("checkCache: Cache with key {0} is expired.", 2));
            }

        }

        private static void EvictionCallback(object key, object value, EvictionReason reason, object state)
        {
            Console.WriteLine();
            Console.WriteLine("/*****************************************************/");
            Console.WriteLine(string.Format("/*  EvictionCallback: Cache with key {0} has expired.  */", key));
            Console.WriteLine("/*****************************************************/");
            Console.WriteLine();
        }
    }
}

最佳答案

要添加接受答案和评论,您可以使用过期的取消 token 强制缓存过期并自动逐出。

int expirationMinutes = 60;
var expirationTime = DateTime.Now.Add(expirationMinutes);
var expirationToken = new CancellationChangeToken(
    new CancellationTokenSource(TimeSpan.FromMinutes(expirationMinutes + .01)).Token);

var cacheEntryOptions = new MemoryCacheEntryOptions()
         // Pin to cache.
         .SetPriority(CacheItemPriority.NeverRemove)
         // Set the actual expiration time
         .SetAbsoluteExpiration(expirationTime)
         // Force eviction to run
         .AddExpirationToken(expirationToken)
         // Add eviction callback
         .RegisterPostEvictionCallback(callback: CacheItemRemoved, state: this); 

`

缺乏内置计时器行为(旧计时器曾经具有这种行为)应该是设计使然,这也是推荐的做法。请参阅:https://github.com/aspnet/Caching/issues/248

关于.Net Core MemoryCache PostEvictionCallback 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42535408/

相关文章:

java - Google Guava Cache,刷新过期超时

caching - 启用缓存后如何持续部署 Web 应用程序?

image - Monotouch 的异步图像下载器/缓存

asp.net - 无法在 helloweb 演示应用程序上运行 k run

c# - 如何像 Vue 一样从父层向 Blazor 组件随机添加 CSS 属性?

c# - 如何使用 .NET 创建 7-Zip 存档?

.net - 如何检查应用程序的 .NET 版本?

c# - ViewData.TemplateInfo.GetFullHtmlFieldId ("PropertyName"的 ASP.NET Core 等效项是什么)?

javascript - ActiveX "Class doesn' t 支持自动化”

ASP.NET SqlBulkCopy 不会在服务器上插入所有记录