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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With