首页 > 解决方案 > 如果我改变从 Net Core IMemoryCache 获得的对象,它会在缓存中更新其状态吗?

问题描述

我在我的 Net Core 代码中使用了 MemoryCache 。

首先,我在缓存中放置了一些字典

var dict = new ConcurrentDictionary<string, int>(/* ...some elements to add... */);
cache.Set("MyCacheKey", dict, _cacheEntryOptions);

如果我从缓存中检索对象,或者只是dict在我调用后更新这个对象cache.Set,它还会更新缓存中对象的状态吗?说,在上面的代码之后我打电话

dict.TryAdd(name, 1);

我需要cache.Set()再次致电还是已经更新?

标签: c#asp.net-core.net-core

解决方案


从下面的代码,到新的值是自动更新到缓存,你不需要再次设置缓存值。

        Dictionary<int, string> test = new Dictionary<int, string>()
        {
            { 0, "a" },
            { 1, "b" }
        };

        _memoryCache.Set("TEST", test);
        if (_memoryCache.TryGetValue("TEST", out object o) && o is Dictionary<int, string> cachedTest)
        {
            cachedTest[0] = "aa";
            cachedTest.Add(2, "c");
        }

        if (_memoryCache.TryGetValue("TEST", out object o2) && o2 is Dictionary<int, string> cachedTest2)
        {
            var updatedValue = cachedTest2[0]; // this give you "aa". Also the dict contains 3 items.
        }

推荐阅读