Created
January 27, 2017 12:47
-
-
Save AdamAndersonFalafelSoftware/0e32afb7790f1021c46b50a8650707a1 to your computer and use it in GitHub Desktop.
MemoryCache helper class async locking test
This file contains 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
void Main() | |
{ | |
var key1Task = new Task<string>(() => ExampleCache.GetItem("key1")); | |
var key2Task = new Task<string>(() => ExampleCache.GetItem("key2")); | |
key1Task.Start(); | |
key2Task.Start(); | |
Task.WaitAll(key1Task, key2Task); | |
key1Task.Result.Dump(); | |
key2Task.Result.Dump(); | |
} | |
// Define other methods and classes here | |
public static class ExampleCache | |
{ | |
private static MemoryCache _cache = new MemoryCache("ExampleCache"); | |
public static string GetItem(string key) | |
{ | |
return AddOrGetExisting(key, () => InitItem(key)); | |
} | |
private static T AddOrGetExisting<T>(string key, Func<T> valueFactory) | |
{ | |
var newValue = new Lazy<T>(valueFactory); | |
var oldValue = _cache.AddOrGetExisting(key, newValue, new CacheItemPolicy()) as Lazy<T>; | |
try | |
{ | |
return (oldValue ?? newValue).Value; | |
} | |
catch | |
{ | |
// Handle cached lazy exception by evicting from cache. Thanks to Denis Borovnev for pointing this out! | |
_cache.Remove(key); | |
throw; | |
} | |
} | |
private static string InitItem(string key) | |
{ | |
Console.WriteLine($"Initializing {key}"); | |
Thread.Sleep(1000); | |
Console.WriteLine($"Finished {key}"); | |
return key.ToUpper(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment