FFMG
FFMG

Reputation: 1257

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.

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

Answers (2)

JacobIRR
JacobIRR

Reputation: 8966

I do this in .net core:

var cacheEntry = _Cache.CreateEntry(accountId);
cacheEntry.Value = myObjectToCache;

Upvotes: 0

Panagiotis Kanavos
Panagiotis Kanavos

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

Related Questions