完全无法定义 System.Runtime.Caching 的 UpdateCallback

Completely Unable to Define the UpdateCallback of System.Runtime.Caching

我在使用 System.Runtime.Caching 库的 CacheEntryUpdateCallback 委托时遇到困难。每当我定义和设置回调时,我都会收到 "CacheItemUpdateCallback must be null" 的 ArgumentException。为什么必须为空?我应该可以设置它然后得到回调。

我在使用 CacheEntryRemovedCallback 委托时没有得到这个。我可以在我的所有项目中可靠地重现这一点。难道我做错了什么?这是一个小示例应用程序:

using System.Runtime.Caching;
class Program {
  static void Main(string[] args) {
    var policy = new CacheItemPolicy();
    policy.SlidingExpiration = TimeSpan.FromSeconds(10);

    // this works
    //policy.RemovedCallback = Removed;

    // this creates the exception
    policy.UpdateCallback = Update;

    MemoryCache.Default.Add("test", "123", policy);
    Console.Read();
  }

  static void Update(CacheEntryUpdateArguments arguments) { }
  static void Removed(CacheEntryRemovedArugments arguments) { }
}

根据文档,您应该使用 Set 而不是 Add

MemoryCache.Add:

The Add and AddOrGetExisting method overloads do not support the UpdateCallback property. Therefore, to set the UpdateCallback property for a cache entry, use the Set method overloads instead.

以下确实可以正常工作:

MemoryCache.Default.Set("test", "123", policy);