From 3465738b13d6b17d17abf6d53baf072b9c9a6b53 Mon Sep 17 00:00:00 2001 From: James Turner Date: Sun, 24 Jul 2022 00:07:50 +0930 Subject: [PATCH] Improve the GetOrSetAsync state machine (#212) Less awaiting paths mean a smaller code size and more "simple" state machine --- src/CacheTower/CacheStack.cs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/CacheTower/CacheStack.cs b/src/CacheTower/CacheStack.cs index ae33a24..c949090 100644 --- a/src/CacheTower/CacheStack.cs +++ b/src/CacheTower/CacheStack.cs @@ -207,6 +207,7 @@ public async ValueTask GetOrSetAsync(string cacheKey, Func> val var currentTime = DateTimeProvider.Now; var cacheEntryPoint = await GetWithLayerIndexAsync(cacheKey); + var cacheEntryStatus = CacheEntryStatus.Stale; if (cacheEntryPoint != default) { if (cacheEntryPoint.CacheEntry.Expiry > currentTime) @@ -215,7 +216,7 @@ public async ValueTask GetOrSetAsync(string cacheKey, Func> val if (settings.StaleAfter.HasValue && cacheEntry.GetStaleDate(settings) < currentTime) { //If the cache entry is stale, refresh the value in the background - _ = RefreshValueAsync(cacheKey, valueFactory, settings, CacheEntryStatus.Stale); + _ = RefreshValueAsync(cacheKey, valueFactory, settings, cacheEntryStatus); } else if (cacheEntryPoint.LayerIndex > 0) { @@ -228,14 +229,16 @@ public async ValueTask GetOrSetAsync(string cacheKey, Func> val else { //Refresh the value in the current thread because we only have expired data (we never return expired data) - return (await RefreshValueAsync(cacheKey, valueFactory, settings, CacheEntryStatus.Expired))!.Value!; + cacheEntryStatus = CacheEntryStatus.Expired; } } else { //Refresh the value in the current thread because we have no existing data - return (await RefreshValueAsync(cacheKey, valueFactory, settings, CacheEntryStatus.Miss))!.Value!; + cacheEntryStatus = CacheEntryStatus.Miss; } + + return (await RefreshValueAsync(cacheKey, valueFactory, settings, cacheEntryStatus))!.Value!; } private async ValueTask BackPopulateCacheAsync(int fromIndexExclusive, string cacheKey, CacheEntry cacheEntry)