我在MemoryCache中使用以下模式:
public static T GetFromCache<T>(string key, Func<T> valueFactory) {
var newValue = new Lazy<T>(valueFactory);
var oldValue = (Lazy<T>)cache.AddOrGetExisting(key, newValue, new CacheItemPolicy());
return (oldValue ?? newValue).Value;
}
并称之为:
var v = GetFromCache<Prop>(request.Key, () => LongCalc());
这工作得很好。但是,当LongCalc抛出异常时,cache.AddOrGetExisting将异常保存到缓存中。
我试图通过以下方式确定何时发生这种情况:
if (oldValue != null && oldValue.Value.GetType() == typeof(Exception)) {
cache.Remove(key, CacheEntryRemovedReason.Evicted);
}
但简单地调用oldValue.Value会引发异常。
如何识别 oldValue 对象是否包含异常并进行相应处理?
阿波罗的战车
MYYA
随时随地看视频慕课网APP
相关分类