Skip to content

Instantly share code, notes, and snippets.

@ascjones
Created March 11, 2015 10:52
Show Gist options
  • Save ascjones/75e74ec05a5de98ba257 to your computer and use it in GitHub Desktop.
Save ascjones/75e74ec05a5de98ba257 to your computer and use it in GitHub Desktop.
Lazy MemoryCache Extensions
public static class MemoryCacheExtensions
{
public static T AddOrGetExistingLazy<T>(this MemoryCache cache, string key, Func<T> valueFactory, CacheItemPolicy cacheItemPolicy)
{
var newValue = new Lazy<T>(valueFactory);
var value = (Lazy<T>)cache.AddOrGetExisting(key, newValue, cacheItemPolicy);
return (value ?? newValue).Value; // Lazy<T> handles the locking itself
}
public static void SetLazy<T>(this MemoryCache cache, string key, T value, CacheItemPolicy cacheItemPolicy)
{
var cacheValue = new Lazy<T>(() => value);
cache.Set(key, cacheValue, cacheItemPolicy);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment