using System; using System.Collections.Generic; using System.Threading; namespace MetaCity.Core.Common { public static class ThreadingUtils { private static bool _initialised; private static Thread _mainThread; private static readonly List ActionsToRunOnMainThread = new(); public static void Initialise() { if (_initialised) return; _initialised = true; _mainThread = Thread.CurrentThread; lock (ActionsToRunOnMainThread) { ActionsToRunOnMainThread.Clear(); } } public static void Destroy() { _initialised = false; } public static bool IsOnMainThread() { return _mainThread != null && _mainThread.Equals(Thread.CurrentThread); } public static void EnqueueActionForMainThread(Action action) { if (!_initialised) return; lock (ActionsToRunOnMainThread) { ActionsToRunOnMainThread.Add(action); } } public static void EnqueueActionForMainThreadOrRunRightNow(Action action) { if (!_initialised) return; if (IsOnMainThread()) action(); else EnqueueActionForMainThread(action); } public static void Update() { lock (ActionsToRunOnMainThread) { foreach (var action in ActionsToRunOnMainThread) action(); ActionsToRunOnMainThread.Clear(); } } } }