From 7170867a9a2650fa5a98b9e2664fb2114a0bf114 Mon Sep 17 00:00:00 2001 From: Jake Mannens Date: Sat, 30 Sep 2023 00:52:18 +1000 Subject: Patched MemoryCache and DB schema --- Util/MemoryCache.cs | 35 +++++++++++++++++++++++++---------- 1 file changed, 25 insertions(+), 10 deletions(-) (limited to 'Util/MemoryCache.cs') diff --git a/Util/MemoryCache.cs b/Util/MemoryCache.cs index ba314cf..bcbd4d2 100644 --- a/Util/MemoryCache.cs +++ b/Util/MemoryCache.cs @@ -10,23 +10,34 @@ public class MemoryCache : IEnumerable> /// Function that will be called to populate the cache in the event of a cache-miss public Func? DataSource { get; init; } - private Dictionary cache = new(); + private Dictionary cache = new(); + + private struct CacheItem { + public DateTime CreateTime { get; set; } + public DateTime LastAccessTime { get; set; } + public TValue Value { get; set; } + } public TValue this[TKey key] { get => GetValue(key); set { Prune(); - cache[key] = (DateTime.Now, value); + cache[key] = new() { + CreateTime = DateTime.Now, + LastAccessTime = DateTime.Now, + Value = value + }; } } public TValue GetValue(TKey key) { bool success = cache.TryGetValue(key, out var result); if(success) { + result.LastAccessTime = DateTime.Now; if(MaxAge is null) - return result.value; - if(result.createTime > DateTime.Now - MaxAge) - return result.value; + return result.Value; + if(result.CreateTime > DateTime.Now - MaxAge) + return result.Value; } if(DataSource is null) @@ -38,7 +49,11 @@ public class MemoryCache : IEnumerable> throw new KeyNotFoundException(); Prune(); - cache[key] = (DateTime.Now, value); + cache[key] = new() { + CreateTime = DateTime.Now, + LastAccessTime = DateTime.Now, + Value = value + }; return value; } @@ -60,10 +75,10 @@ public class MemoryCache : IEnumerable> foreach(var kv in cache) { // Don't return expired cache items if(expiry is not null) - if(kv.Value.createTime < expiry) + if(kv.Value.CreateTime < expiry) continue; - yield return new KeyValuePair(kv.Key, kv.Value.value); + yield return new KeyValuePair(kv.Key, kv.Value.Value); } } @@ -76,7 +91,7 @@ public class MemoryCache : IEnumerable> // specified, remove expired cache items. if(expiry is not null) { foreach(var kv in cache) { - if(kv.Value.createTime < expiry) + if(kv.Value.CreateTime < expiry) cache.Remove(kv.Key); } } @@ -87,7 +102,7 @@ public class MemoryCache : IEnumerable> return; var toRemove = cache - .OrderBy(kv => kv.Value.createTime) + .OrderBy(kv => kv.Value.LastAccessTime) .Take(cache.Count() - (int) MaxItems + 1) .Select(kv => kv.Key) .ToArray(); -- cgit v1.3