MemoryCache 不更新 Updatecallback 中的项目

MemoryCache do not update item in Updatecallback

我编写了以下代码(在 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

结果如下:

谁能解释为什么我得不到 "value2" 作为结果?

将新项目分配给 UpdatedCacheItem 时,您还必须分配新策略。这些文档相当空泛(UpdatedCacheItem seems to say it's required, 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);
    }

IsPolicyValid returns false 如果 policynull.


1 行情:

you must assign a CacheItem object to the UpdatedCacheItem property and assign a CacheItemPolicy object to the UpdatedCacheItemPolicy property

对比:

you can optionally assign a CacheItemPolicy object to the UpdatedCacheItemPolicy property