dotNetCore v3-MemoryCache主动过期

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

namespace ConsoleApp4
{
    class Program
    {
        static void Main(string[] args)
        {
            MemoryCache cache = new MemoryCache(new MemoryCacheOptions()
            {
            });

            CancellationTokenSource tokenSource = new CancellationTokenSource();

            var option = new MemoryCacheEntryOptions()
            {
                AbsoluteExpiration = DateTime.Now.AddSeconds(20)
            };
            option.RegisterPostEvictionCallback((key, value, reason, obj) =>
            {
                Console.WriteLine(reason);
            });

            option.AddExpirationToken(new CancellationChangeToken(tokenSource.Token));

            cache.Set("key", "value", option);

            System.Threading.Thread.Sleep(2000);

            tokenSource.CancelAfter(2000);         

      
            Console.Read();
        }
    }
}
 

发布了445 篇原创文章 · 获赞 71 · 访问量 28万+

猜你喜欢

转载自blog.csdn.net/dxm809/article/details/104184581
今日推荐