Created
March 11, 2015 10:52
-
-
Save ascjones/75e74ec05a5de98ba257 to your computer and use it in GitHub Desktop.
Lazy MemoryCache Extensions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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