C# MemoryCache获取/设置并分配给变量
我已经在本地测试了一些代码,并阅读了很多SO帖子,但我仍然有点困惑MemoryCache在某些场景中是如何工作的。因此,问题涉及以下代码:C# MemoryCache获取/设置并分配给变量,c#,multithreading,asynchronous,caching,thread-safety,C#,Multithreading,Asynchronous,Caching,Thread Safety,我已经在本地测试了一些代码,并阅读了很多SO帖子,但我仍然有点困惑MemoryCache在某些场景中是如何工作的。因此,问题涉及以下代码: class Program { static void Main(string[] args) { var test = new Test(); test.TestingMethod(); } } public class Test { private readonly MemoryCa
class Program
{
static void Main(string[] args)
{
var test = new Test();
test.TestingMethod();
}
}
public class Test
{
private readonly MemoryCache MemoryCache = MemoryCache.Default;
private CacheItemPolicy policy = null;
private CacheEntryRemovedCallback callback = null;
public void TestingMethod()
{
var ints = new List<int>();
for (var i = 0; i <= 1000; i++)
{
ints.Add(i);
}
callback = this.MyCachedItemRemovedCallback;
policy = new CacheItemPolicy
{
Priority = CacheItemPriority.Default,
AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(2),
RemovedCallback = callback
};
MemoryCache.Set("ints", ints, policy);
var intsCached = (List<int>) MemoryCache.Get("ints");
Task.Delay(TimeSpan.FromSeconds(15)).Wait();
MemoryCache.Set("ints", new List<int>() {1}, policy);
foreach (var intCached in intsCached)
{
Console.WriteLine(intCached);
}
Console.ReadLine();
}
void MyCachedItemRemovedCallback(CacheEntryRemovedArguments arguments)
{
Console.WriteLine("Expired");
}
}
类程序
{
静态void Main(字符串[]参数)
{
var测试=新测试();
test.TestingMethod();
}
}
公开课考试
{
private readonly MemoryCache MemoryCache=MemoryCache.Default;
私有CacheItemPolicy策略=null;
private CacheEntryRemovedCallback=null;
公共无效测试方法()
{
var ints=新列表();
for(var i=0;iMemoryCache
(或存储值的任何其他实体)将不会在将同名项设置为不同值时神奇地更新列表内容。即,如果改为MemoryCache.set(“ints”,42,policy);
看起来您希望值(intsCached
)在分配给以下对象后很长一段时间内进行计算:
var intsCached = (List<int>) MemoryCache.Get("ints");
请阅读仅更新到我的主要问题此行为与MemoryCache无关。您在变量intsCached
中存储了一个包含1000项的列表。仅此而已。其他一切都是噪音。如果您从MemoryCache中重新提取并迭代该集合,它将包含1项。这不是对内存缓存列表的引用吗h?这不是我读到的MemoryCache中存储的内容的副本?它是对一个列表的引用,该列表曾经也存储在MemoryCache中,但现在不再是了。
Func<List<int>> intsCached = () => (List<int>) MemoryCache.Get("ints");
...
foreach (var intCached in intsCached())
...