System.Runtime.Caching.MemoryCache ObjectCache
suggest changeThis function returns an item from the cache. If the key is missing, it stores the result of valueFetchFactory. _cacheContainer is the MemoryCache instance. The catch block hides every failure, including exceptions thrown by valueFetchFactory, and returns default(TValue).
public static TValue GetExistingOrAdd<TValue>(string key, double minutesForExpiration, Func<TValue> valueFetchFactory)
{
try
{
//The Lazy class provides Lazy initialization which will evaluate
//the valueFetchFactory only if item is not in the cache.
var newValue = new Lazy<TValue>(valueFetchFactory);
//Setup the cache policy if item will be saved back to cache.
CacheItemPolicy policy = new CacheItemPolicy()
{
AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(minutesForExpiration)
};
// Returns the existing item, or null if newValue was added.
var cachedItem = _cacheContainer.AddOrGetExisting(key, newValue, policy) as Lazy<TValue>;
return (cachedItem ?? newValue).Value;
}
catch (Exception excep)
{
return default(TValue);
}
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents