我在使用System.Runtime.Caching库的CacheEntryUpdateCallback委托时遇到了困难.每当我定义和设置回调时,我得到一个ArgumentException,“CacheItemUpdateCallback必须为null”.为什么必须为空?我应该能够设置它然后获得回调.
使用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
AddandAddOrGetExistingmethod overloads do not support the UpdateCallback property. Therefore,to set the UpdateCallback property for a cache entry,use theSetmethod overloads instead.
确实工作没有问题:
MemoryCache.Default.Set("test",policy);