Skip to content

Instantly share code, notes, and snippets.

@cdemi
Last active July 23, 2021 02:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save cdemi/286de3dd4cd7a50004810ebda73cd07d to your computer and use it in GitHub Desktop.
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/
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;
}
}
@cdemi
Copy link
Author

cdemi commented May 8, 2016

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment