MemoryCache获取/设置并分配给变量

问题描述 投票:0回答:1

我一直在本地测试一些代码,并阅读了相当多的SO帖子,但我仍然有点困惑MemoryCache在某些情况下如何工作。所以问题涉及以下代码:

 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");
    }
}

在这个TestMethod的控制台输出中,我在单独的行上获得过期1 - 1000

为什么我会得到1-1000而不是我们在到期后设置的1?这个列表不是指同一个参考吗?

c# multithreading asynchronous caching thread-safety
1个回答
1
投票

当您将具有相同名称的条目设置为不同的值时,MemoryCache(或任何其他存储值的实体)不会神奇地更新List的内容。即怎么样,如果你做MemoryCache.Set("ints", 42, policy);而不是?

看起来你期望值(intsCached)在分配给它后很久就被计算出来:

  var intsCached = (List<int>) MemoryCache.Get("ints");

intsCached是在该线计算的,不再知道它来自哪里。

如果你想要“变量”来记住它的来源并始终从该位置获得最新值 - 每次使用Func来计算它:

  Func<List<int>> intsCached = () => (List<int>) MemoryCache.Get("ints");
  ...
  foreach (var intCached in intsCached()) 
  ...
© www.soinside.com 2019 - 2024. All rights reserved.