MemoryCache 不存储 IReadOnlyList
MemoryCache doesn't store IReadOnlyList
我厌倦了将填充的 IReadOnlyList 设置为缓存,但它始终为空:
CacheItemPolicy cip = new CacheItemPolicy(); // no expiration
IReadOnlyList<T> dataList = [populate var]
if (dataList != null)
{
MemoryCache.Default.Set(_cacheKey, dataList, cip);
}
缓存中未设置任何内容。但是如果我把它改成:
List<T> list = null;
CacheItemPolicy cip = new CacheItemPolicy(); // no expiration
IReadOnlyList<T> dataList = [populate var]
if (dataList != null)
{
list = dataList.ToList();
MemoryCache.Default.Set(_cacheKey, list, cip);
}
有效。 MemoryCache 不支持接口或 IReadOnlyList 对象吗?
MemoryCache 正在缓存对第一个示例中的列表的引用和第二个示例中的列表副本。
这一定是您的代码重用了作为 dataList 传入的列表,因此您需要缓存一个副本。调用 ToList() 进行复制。
我厌倦了将填充的 IReadOnlyList 设置为缓存,但它始终为空:
CacheItemPolicy cip = new CacheItemPolicy(); // no expiration
IReadOnlyList<T> dataList = [populate var]
if (dataList != null)
{
MemoryCache.Default.Set(_cacheKey, dataList, cip);
}
缓存中未设置任何内容。但是如果我把它改成:
List<T> list = null;
CacheItemPolicy cip = new CacheItemPolicy(); // no expiration
IReadOnlyList<T> dataList = [populate var]
if (dataList != null)
{
list = dataList.ToList();
MemoryCache.Default.Set(_cacheKey, list, cip);
}
有效。 MemoryCache 不支持接口或 IReadOnlyList 对象吗?
MemoryCache 正在缓存对第一个示例中的列表的引用和第二个示例中的列表副本。
这一定是您的代码重用了作为 dataList 传入的列表,因此您需要缓存一个副本。调用 ToList() 进行复制。