MemoryCache不更新Updatecallback中的项目

时间:2016-09-08 08:29:36

标签: c# memorycache

我编写以下代码(在linqpad中)来演示我的问题:

void Main()
{
    var waitEvent = new AutoResetEvent(false);
    MemoryCache.Default.Set(
        "test", 
        "value", 
        new CacheItemPolicy
        {
            AbsoluteExpiration = DateTimeOffset.UtcNow.Add(TimeSpan.FromSeconds(5)),
            UpdateCallback = (CacheEntryUpdateArguments e) => {
                waitEvent.Set();
                e.Dump();
                e.UpdatedCacheItem = new CacheItem(e.Key, "value2");
            }
        });

    MemoryCache.Default.Get("test").Dump();
    waitEvent.WaitOne();
    waitEvent.WaitOne(TimeSpan.FromSeconds(10));


    MemoryCache.Default.Get("test").Dump();

}

// Define other methods and classes here

结果如下:

enter image description here

任何人都可以解释为什么我不能得到“value2”作为结果吗?

1 个答案:

答案 0 :(得分:0)

在将新项目分配给UpdatedCacheItem时,您还必须指定新策略。这些文档非常荒谬(UpdatedCacheItem似乎说它是必需的,UpdatedCacheItemPolicy似乎暗示它是可选的 1 )。但是,消息来源明确表示:

// invoke update callback
try {
    CacheEntryUpdateArguments args = new CacheEntryUpdateArguments(cache, reason, entry.Key, null);
    entry.CacheEntryUpdateCallback(args);
    Object expensiveObject = (args.UpdatedCacheItem != null) ? args.UpdatedCacheItem.Value : null;
    CacheItemPolicy policy = args.UpdatedCacheItemPolicy;
    // Dev10 861163 - Only update the "expensive" object if the user returns a new object,
    // a policy with update callback, and the change monitors haven't changed.  (Inserting
    // with change monitors that have already changed will cause recursion.)
    if (expensiveObject != null && IsPolicyValid(policy)) {
          cache.Set(entry.Key, expensiveObject, policy);
    }
    else {
          cache.Remove(entry.Key);
    }
如果IsPolicyValidfalse,则

policy会返回null

1 引号:

  

您必须将CacheItem对象分配给UpdatedCacheItem属性,并将CacheItemPolicy对象分配给UpdatedCacheItemPolicy属性

  

您可以选择将CacheItemPolicy对象分配给UpdatedCacheItemPolicy属性