Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update existing cache using HybridCache in .NET 9

I am trying to see if I can update a cached collection (in memory) using HybridCache.

When using MemoryCache, I can do something like this, this was an easy "hack" to update collection without removing it from memory:

var list1 = new List<string>() { "a", "b", "c" };
IMemoryCache cache = new MemoryCache(new MemoryCacheOptions());
cache.Set("Key", list1);

if (cache.TryGetValue<List<string>>("Key", out List<string>? result))
{
    result!.Add("d");
}

var list = cache.Get("Key");

EDIT: even if "by default, HybridCache uses MemoryCache", it doesn't work like the MemoryCache, using the reference types. There are some methods which are not implemented, such as TryGetValue, I just wanted to see if it was possible or there is an alternate way, obviously you can drop the key.

like image 762
Zulander Avatar asked Sep 02 '25 03:09

Zulander


1 Answers

I don't know the specific details of this behaviour in HybridCache from Microsoft, but can I suggest taking a look at FusionCache (shameless plug) as an alternative hybrid cache?

The behaviour you are looking for will work with FusionCache by default, unless you explicitly opt-in to using Auto-Clone.

FusionCache has been battle tested in production for years, has basically the same design as HybridCache but with more flexibility, more features, extra resiliency and is even already used by Microsoft itself (see here).

For a quick intro there's this On .NET episode.

Hope this helps.

like image 193
Jody Donetti Avatar answered Sep 04 '25 23:09

Jody Donetti