我编写以下代码(在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”作为结果吗?
答案 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);
}
如果IsPolicyValid
为false
,则 policy
会返回null
。
1 引号:
您必须将
CacheItem
对象分配给UpdatedCacheItem
属性,并将CacheItemPolicy
对象分配给UpdatedCacheItemPolicy
属性
与
您可以选择将
CacheItemPolicy
对象分配给UpdatedCacheItemPolicy
属性