Last active
July 23, 2021 02:56
-
-
Save cdemi/286de3dd4cd7a50004810ebda73cd07d to your computer and use it in GitHub Desktop.
Sample Cache Aside Implementation in C# as a Generic Extension Method. Part of Blog: https://blog.cdemi.io/design-patterns-cache-aside-pattern/
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
private static ConcurrentDictionary<string, object> concurrentDictionary = new ConcurrentDictionary<string, object>(); | |
public static T CacheAside<T>(this ICacheManager cacheManager, Func<T> execute, TimeSpan? expiresIn, string key) | |
{ | |
var cached = cacheManager.Get(key); | |
if (EqualityComparer<T>.Default.Equals(cached, default(T))) | |
{ | |
object lockOn = concurrentDictionary.GetOrAdd(key, new object()); | |
lock (lockOn) | |
{ | |
cached = cacheManager.Get(key); | |
if (EqualityComparer<T>.Default.Equals(cached, default(T))) | |
{ | |
var executed = execute(); | |
if (expiresIn.HasValue) | |
cacheManager.Set(key, executed, expiresIn.Value); | |
else | |
cacheManager.Set(key, executed); | |
return executed; | |
} | |
else | |
{ | |
return cached; | |
} | |
} | |
} | |
else | |
{ | |
return cached; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://blog.cdemi.io/design-patterns-cache-aside-pattern/