Created
June 27, 2019 14:12
-
-
Save TWolverson/90d85fb966ee19387d15799db81384c0 to your computer and use it in GitHub Desktop.
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 Helpers | |
{ | |
// this method must be non-async because the caller doesn't understand Tasks | |
// it also must be static for *reasons* | |
public static string GetApplicationValue(string appType, string listType, string key) | |
{ | |
RefreshCache(); // this needs to block so that the cache is refreshed before trying to return a result | |
// pseudocode | |
return Cache.SingleOrDefault(item => item.Key == key); | |
} | |
private static DateTime lastUpdatedTime = DateTime.MinValue; | |
private static SemaphoreSlim throttle = new SemaphoreSlim(1); | |
private static async void RefreshCache() | |
{ | |
try | |
{ | |
// stop more than one thread from trying to update the cache at a time | |
await throttle.WaitAsync(); | |
if(lastUpdatedTime < DateTime.Now.AddMinutes(-10)) | |
{ | |
// pseudocode | |
// this method must be async so that the HttpClient methods can be awaited | |
var data = await new HttpClient().GetAsync("/api/data"); | |
// pseudocode | |
Cache.NewData(data); | |
lastUpdatedTime = DateTime.Now; | |
} | |
} | |
finally | |
{ | |
// make sure the semaphore is always released otherwise every thread that enters will be stuck here forever | |
throttle.Release(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment