From e6ef71bae149b0d94055141075a84783f91e7c52 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Fri, 20 May 2022 17:39:05 -0400 Subject: add tick cache to asset propagation --- .../Framework/Utilities/TickCacheDictionary.cs | 26 ++++++++++++++++++++++ 1 file changed, 26 insertions(+) (limited to 'src/SMAPI/Framework/Utilities') diff --git a/src/SMAPI/Framework/Utilities/TickCacheDictionary.cs b/src/SMAPI/Framework/Utilities/TickCacheDictionary.cs index 20d206e2..7732ace8 100644 --- a/src/SMAPI/Framework/Utilities/TickCacheDictionary.cs +++ b/src/SMAPI/Framework/Utilities/TickCacheDictionary.cs @@ -48,4 +48,30 @@ namespace StardewModdingAPI.Framework.Utilities return this.Cache.Remove(cacheKey); } } + + /// An in-memory dictionary cache that stores data for the duration of a game update tick. + /// The dictionary key type. + internal class TickCacheDictionary : TickCacheDictionary + where TKey : notnull + { + /********* + ** Public methods + *********/ + /// Get a value from the cache, fetching it first if it's not cached yet. + /// The unique key for the cached value. + /// Get the latest data if it's not in the cache yet. + public TValue GetOrSet(TKey cacheKey, Func get) + { + object? value = base.GetOrSet(cacheKey, () => get()!); + + try + { + return (TValue)value; + } + catch (Exception ex) + { + throw new InvalidCastException($"Can't cast value of the '{cacheKey}' cache entry from {value?.GetType().FullName ?? "null"} to {typeof(TValue).FullName}.", ex); + } + } + } } -- cgit