[英]MemoryCache only add if not exist in .NET Core? (similar to MemoryCache.Add in Framework)
.NET Core has a memory cache class Microsoft.Extensions.Caching.Memory
, you can set a value using the CacheExtensions
cache. .NET Core has a memory cache class Microsoft.Extensions.Caching.Memory
, you can set a value using the CacheExtensions
cache.
But I would like to add only if the value does not exist yet.但我只想在该值尚不存在的情况下添加。 Is it possible to do that with Microsoft.Extensions.Caching.Memory
?是否可以使用Microsoft.Extensions.Caching.Memory
做到这一点?
If not, what would be the equivalent method for MemoryCache.Add(... )
in .NET 4.8 (it returns false in case of duplicates), using .NET Core 6.0?如果不是,那么使用 .NET Core 6.0 的 .NET 4.8 中的MemoryCache.Add(... )
的等效方法是什么(如果重复则返回 false)?
Use GetOrCreate instead, or GetOrCreateAsync if the value needs to be generated asynchronously.请改用GetOrCreate ,如果需要异步生成值,请使用GetOrCreateAsync 。
.NET Framework's Add does as well, it calls AddOrGetExisting
and returns true
if there was no existing value: .NET 框架的Add也是如此,它调用AddOrGetExisting
并在没有现有值时返回true
:
public override bool Add(CacheItem item, CacheItemPolicy policy) {
CacheItem existingEntry = AddOrGetExisting(item, policy);
return (existingEntry == null || existingEntry.Value == null);
}
Add
hides what's actually going and is easy to implement yourself if you absolutely have to Add
隐藏了实际情况,如果您绝对需要,您自己很容易实现
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.