Reputation: 1257
.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?
Upvotes: 0
Views: 902
Reputation: 8966
I do this in .net core:
var cacheEntry = _Cache.CreateEntry(accountId);
cacheEntry.Value = myObjectToCache;
Upvotes: 0
Reputation: 131704
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
Upvotes: 1