You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MemoryCache.Remove()方法为何并非总能正常生效?

MemoryCache.Remove() 偶尔失效问题求助

我给MemoryCache写了个包装类,逻辑简单,还支持设置默认缓存时长。但在回归测试中发现Remove()方法并非100%生效——有时测试失败,不改代码重新跑又能成功。调试时发现缓存根本没刷新,缓存项始终保留第一次插入的值。

测试逻辑如下:

// 向数据库插入记录
// 创建缓存
// 向数据库插入第二条记录
// 移除缓存
// 创建新缓存

有没有人遇到过类似问题?

我的缓存包装类代码:

internal class CacheService : ICacheService
{
    private readonly IMemoryCache _memoryCache;
    private const int DefaultCacheDuration = 3600;

    public CacheService(IMemoryCache memoryCache)
    {
        _memoryCache = memoryCache;
    }

    public void Create(string? key, object? value, int durationInMinutes)
    {
        if (string.IsNullOrWhiteSpace(key) || value == null) return;

        if (durationInMinutes <= 0) durationInMinutes = DefaultCacheDuration;
        _memoryCache.Set(key, value, TimeSpan.FromMinutes(durationInMinutes));
    }

    public T? Get<T>(string? key)
    {
        if (string.IsNullOrWhiteSpace(key))
        {
            return default;
        }
        return _memoryCache.TryGetValue<T>(out var value) ? value : default;
    }

    public void Remove(string? key)
    {
        if (!string.IsNullOrWhiteSpace(key))
        {
            _memoryCache.Remove(key);
        }
    }
}

补充说明:

  • 缓存键为常量,不会被空值检查拦截
  • ICacheService 以 DependencyInjectionScope.Transient 作用域注入
  • 回归测试是单条长测试,缓存仅初始化一次,注入时从同一实例池获取
  • 测试全程单线程运行,未调用 MemoryCache.Clear()

内容的提问来源于stack exchange,提问作者Bagzli

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 23:45:24