【问题标题】:Completely Unable to Define the UpdateCallback of System.Runtime.Caching完全无法定义 System.Runtime.Caching 的 UpdateCallback
【发布时间】:2015-04-10 19:10:57
【问题描述】:

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

我在使用 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) { }
}

【问题讨论】:

    标签: c# .net caching


    【解决方案1】:

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

    MemoryCache.Add:

    AddAddOrGetExisting 方法重载不支持 UpdateCallback 属性。因此,要为缓存条目设置 UpdateCallback 属性,请改用 Set 方法重载。

    以下确实可以正常工作:

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

    【讨论】:

    • 太好了,这正是我想要的。
    猜你喜欢
    • 1970-01-01
    • 2018-04-17
    • 2021-02-03
    • 1970-01-01
    • 2015-06-25
    • 2015-08-17
    • 2012-12-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多