作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
在当前实现中 IMemoryCache
接口(interface)有以下方法:
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());
}
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
, 等等日期 (
https://github.com/aspnet/Caching/blob/12f998d69703fb0f62b5cb1c123b76d63e0d04f0/src/Microsoft.Extensions.Caching.Abstractions/MemoryCacheExtensions.cs),但是
GetOrCreate
当我们创建一个新条目时,方法不支持那种类型的“per-entry-expiration-date”。
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();
});
string timestamp = cache.GetOrCreate("timestamp", entry =>
{
entry.SlidingExpiration = TimeSpan.FromSeconds(5);
return DateTime.Now.ToString();
});
MemoryCacheEntryOptions
可在
ICacheEntry
上获得.
关于caching - 内存缓存 GetOrCreate 和 MemoryCacheEntryOptions,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50247519/
在当前实现中 IMemoryCache接口(interface)有以下方法: bool TryGetValue(object key, out object value); ICacheEntry C
我是一名优秀的程序员,十分优秀!