Caching 内存中缓存获取或使用MemoryCacheEntryOptions创建

Caching 内存中缓存获取或使用MemoryCacheEntryOptions创建,caching,asp.net-core,Caching,Asp.net Core,在当前实现中,IMemoryCache接口有以下方法: bool TryGetValue(object key, out object value); ICacheEntry CreateEntry(object key); void Remove(object key); 我们可以通过以下方式查询缓存中的条目: //first way if (string.IsNullOrEmpty (cache.Get<string>("timestamp"))) { cache.Set&

在当前实现中,
IMemoryCache
接口有以下方法:

bool TryGetValue(object key, out object value);
ICacheEntry CreateEntry(object key);
void Remove(object key);
我们可以通过以下方式查询缓存中的条目:

//first way
if (string.IsNullOrEmpty
(cache.Get<string>("timestamp")))
{
  cache.Set<string>("timestamp", DateTime.Now.ToString());
}

//second way
if (!cache.TryGetValue<string>
("timestamp", out string timestamp))
{
    //
    cache.Set<string>("timestamp", DateTime.Now.ToString());
}
如上所述,
Set
方法接受
MemoryCacheEntryOptions
或任何
absoluteExpirationRelativeToNow
absoluteExpiration
等日期(),但
GetOrCreate
方法不支持在创建新条目时使用那种类型的“每个条目到期日期”

我想弄清楚我是否遗漏了什么,或者我是否应该做一个公关来添加这些方法

附件:

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

在此处打开了一个问题:为了获得更多反馈。

我不确定是否理解正确,但您可以将收到的条目上的所有“每个条目过期日期”选项设置为出厂参数:

string timestamp = cache.GetOrCreate("timestamp", entry =>
{
    entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(5);

    return DateTime.Now.ToString();
});


所有
MemoryCacheEntryOptions
都可以在
ICacheEntry

Hmm上找到……是的……看起来所有
Set
方法都只会设置一个条目的值+您指定的任何“每个条目的过期日期”,并且您可以在该工厂内访问这些选项,因为它们是
ICacheEntry
的一部分。为什么我没有想到这一点?我只想分享我的2美分:如果你复制粘贴第一个代码块,插入你的逻辑,在其中有一个异步任务,然后更改为
异步条目
,因为你的编辑器开始抱怨,别忘了也更改为
\u cache.GetOrCreateAsync
,否则这个过期将不起作用!您仍然可以等待逻辑并返回一个普通对象。
string timestamp = cache.GetOrCreate("timestamp", entry =>
{
    entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(5);

    return DateTime.Now.ToString();
});
string timestamp = cache.GetOrCreate("timestamp", entry =>
{
    entry.SlidingExpiration = TimeSpan.FromSeconds(5);

    return DateTime.Now.ToString();
});