首页 > 解决方案 > MemoryCache 不接受任何过期时间

问题描述

我有一个非常简单的代码,但它的作用完全奇怪。这是一个简单的 Cache 抽象,如下所示:

public class CacheAbstraction
{
    private MemoryCache _cache;

    public CacheAbstraction()
    {
        _cache = new MemoryCache(new MemoryCacheOptions { });
    }

    public async Task<T> GetItemAsync<T>(TimeSpan duration, Func<Task<T>> factory, 
                                         [CallerMemberName] string identifier = null ) where T : class
    {
        return await _cache.GetOrCreateAsync<T>(identifier, async x =>
        {
            x.SetAbsoluteExpiration(DateTime.UtcNow.Add(duration));
            T result = null;
            result = await factory();
            return result;
        });
    }
}

现在有趣的部分:我正在通过 1h - 1d 的过期时间

如果我在测试套件中运行它,一切都很好。

如果我将其作为 .net 核心应用程序运行,则过期始终设置为“现在”,并且该项目在下一次缓存检查时过期。哇!?

标签: c#cachingmemorycache

解决方案


推荐阅读