From 219696275df054d25cd385f950eb01ee33312e76 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sat, 11 Jan 2020 13:20:37 -0500 Subject: fix errors due to async threads creating content managers --- src/SMAPI/Framework/InternalExtensions.cs | 70 +++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) (limited to 'src/SMAPI/Framework/InternalExtensions.cs') diff --git a/src/SMAPI/Framework/InternalExtensions.cs b/src/SMAPI/Framework/InternalExtensions.cs index c3155b1c..8b45e196 100644 --- a/src/SMAPI/Framework/InternalExtensions.cs +++ b/src/SMAPI/Framework/InternalExtensions.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Reflection; +using System.Threading; using Microsoft.Xna.Framework.Graphics; using StardewModdingAPI.Framework.Events; using StardewModdingAPI.Framework.Reflection; @@ -83,6 +84,75 @@ namespace StardewModdingAPI.Framework return exception; } + /**** + ** ReaderWriterLockSlim + ****/ + /// Run code within a read lock. + /// The lock to set. + /// The action to perform. + public static void InReadLock(this ReaderWriterLockSlim @lock, Action action) + { + @lock.EnterReadLock(); + try + { + action(); + } + finally + { + @lock.ExitReadLock(); + } + } + + /// Run code within a read lock. + /// The action's return value. + /// The lock to set. + /// The action to perform. + public static TReturn InReadLock(this ReaderWriterLockSlim @lock, Func action) + { + @lock.EnterReadLock(); + try + { + return action(); + } + finally + { + @lock.ExitReadLock(); + } + } + + /// Run code within a write lock. + /// The lock to set. + /// The action to perform. + public static void InWriteLock(this ReaderWriterLockSlim @lock, Action action) + { + @lock.EnterWriteLock(); + try + { + action(); + } + finally + { + @lock.ExitWriteLock(); + } + } + + /// Run code within a write lock. + /// The action's return value. + /// The lock to set. + /// The action to perform. + public static TReturn InWriteLock(this ReaderWriterLockSlim @lock, Func action) + { + @lock.EnterWriteLock(); + try + { + return action(); + } + finally + { + @lock.ExitWriteLock(); + } + } + /**** ** Sprite batch ****/ -- cgit