.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
?
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?
Use GetOrCreate instead, or GetOrCreateAsync if the value needs to be generated asynchronously.
.NET Framework's Add does as well, it calls AddOrGetExisting
and returns true
if there was no existing value:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.