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

关于IMemoryCache的GetOrCreate方法缺失MemoryCacheEntryOptions支持的问询

关于IMemoryCache扩展方法的疑问探讨

最近在研究IMemoryCache的实现,先给大家梳理下当前这个接口的核心方法,它包含三个基础成员:

bool TryGetValue(object key, out object value);
ICacheEntry CreateEntry(object key);
void Remove(object key);

日常开发中,我们常用两种方式查询缓存条目:

  • 第一种是借助Get方法做判断:
// first way
if (string.IsNullOrEmpty(cache.Get<string>("timestamp"))) {
    cache.Set<string>("timestamp", DateTime.Now.ToString());
}
  • 第二种是用TryGetValue做更严谨的存在性校验:
// second way
if (!cache.TryGetValue<string>("timestamp", out string timestamp)) {
    // cache.Set<string>("timestamp", DateTime.Now.ToString());
}

除此之外,还有一个GetOrCreate扩展方法,它的设计逻辑是当缓存不存在时,通过传入的工厂方法创建新的缓存条目,现有实现代码如下:

public static TItem GetOrCreate<TItem>(this IMemoryCache cache, object key, Func<ICacheEntry, TItem> factory) {
    object obj;
    if (!cache.TryGetValue(key, out obj)) {
        ICacheEntry entry = cache.CreateEntry(key);
        obj = (object)factory(entry);
        entry.SetValue(obj);
        entry.Dispose();
    }
    return (TItem)obj;
}

这里我发现了一个问题:我们知道Set方法支持传入MemoryCacheEntryOptions,或者直接指定absoluteExpirationRelativeToNow、absoluteExpiration这类参数来配置缓存的过期策略,但现有的GetOrCreate方法在创建新条目时,并没有提供这类条目级过期配置的入口。

我想确认一下,是不是我遗漏了什么,其实已经有支持该功能的重载方法了?还是说确实需要提交PR来补充相关的扩展方法,让GetOrCreate也能支持自定义过期配置?

另外附上用到的辅助扩展方法代码:

public static ICacheEntry SetValue(this ICacheEntry entry, object value) {
    entry.Value = value;
    return entry;
}

我已经在项目相关仓库提交了Issue来寻求官方反馈。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 06:32:44