c# - 如果我改变从 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()
再次致电还是已经更新?
解决方案
从下面的代码,到新的值是自动更新到缓存,你不需要再次设置缓存值。
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.
}
推荐阅读
- laravel - 有没有办法使用 laravel eloquent 中的键获取键的值(类似于从数组中的键获取值)
- android - 如何使用 Flutter 将相机捕获转换为 PDF 并显示?
- zabbix - Zabbix API 用于获取应用程序使用的流量的详细信息
- python - 填充由元胞自动机生成的洞穴
- python-3.x - 同一时区的python时区问题
- python - 如何在子组中过滤(熊猫)
- javascript - use for loop in flatlist react native
- c# - 从泛型方法调用重载的泛型方法
- node.js - 如何在编译期间向我的 js 文件添加额外的导入。想要为我的反应组件主题化
- c# - 将特定接口实现映射到接口目标