I am using the following pattern with 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;
}
And call it:
var v = GetFromCache<Prop>(request.Key, () => LongCalc());
This works well enough. However, when LongCalc
throws an exception, cache.AddOrGetExisting
saves the exception into the cache.
I am trying to identify when that happens via:
if (oldValue != null && oldValue.Value.GetType() == typeof(Exception)) {
cache.Remove(key, CacheEntryRemovedReason.Evicted);
}
but simply calling oldValue.Value
throws an exception.
How can I identify whether oldValue object contains an exception and deal with it accordingly?