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

如何在IMemoryCache中正确实现计数器自增并处理键不存在场景

正确实现代码

你可以直接通过GetOrCreate封装的存在判断逻辑完成需求,示例代码如下:

// IMemoryCache 已注入到类字段 _cache
public void IncreaseCounter(string key)
{
    // 键存在则直接返回已有值,不存在则执行工厂方法初始化值为0
    int currentCount = _cache.GetOrCreate<int>(key, cacheEntry =>
    {
        // 可按需配置缓存策略,比如设置1小时绝对过期
        cacheEntry.AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(1);
        return 0;
    });
    // 自增后回写缓存
    _cache.Set(key, currentCount + 1);
}

逻辑说明

  • GetOrCreate 已经内置了键存在性判断,不需要你手动写if判断键是否存在:当键首次访问时,工厂方法会执行返回初始值0,自增后缓存值为1,符合你的要求。
  • 你原有代码存在变量名拼写错误(currectCount 和 currentCount 不一致),会导致编译失败,上述代码已修正该问题。

高并发场景优化

由于IMemoryCache的读写操作本身不是原子操作,高并发场景下直接读写会出现计数丢失的问题,可通过加锁保证原子性:

// 在类中定义锁对象
private readonly object _counterLock = new();

public void IncreaseCounter(string key)
{
    lock (_counterLock)
    {
        int currentCount = _cache.GetOrCreate<int>(key, cacheEntry =>
        {
            cacheEntry.AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(1);
            return 0;
        });
        _cache.Set(key, currentCount + 1);
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 22:06:03