From ce488a0d4effbf08c311e50a8e2009d1efd84b1d Mon Sep 17 00:00:00 2001 From: Brant Martin Date: Mon, 17 Oct 2016 05:52:10 -0400 Subject: [PATCH] Add new methods to safely invoke actions on the game thread, in blocking and callback flavors. --- PistonServer/ServerManager.cs | 70 ++++++++++++++++++++++++++++++++++- 1 file changed, 68 insertions(+), 2 deletions(-) diff --git a/PistonServer/ServerManager.cs b/PistonServer/ServerManager.cs index 82303b0..95f1a63 100644 --- a/PistonServer/ServerManager.cs +++ b/PistonServer/ServerManager.cs @@ -57,9 +57,75 @@ namespace Piston.Server MyFinalBuildConstants.APP_VERSION = gameVersion ?? 0; } - public void Invoke(Action action) + /// + /// Invokes an action on the game thread and blocks until completion + /// + /// + public void GameAction(Action action) { - MySandboxGame.Static.Invoke(action); + try + { + if (Thread.CurrentThread == MySandboxGame.Static.UpdateThread) + { + action(); + } + else + { + AutoResetEvent e = new AutoResetEvent(false); + + MySandboxGame.Static.Invoke(() => + { + try + { + action(); + } + catch (Exception ex) + { + //log + } + finally + { + e.Set(); + } + }); + + //timeout so we don't accidentally hang the server + e.WaitOne(60000); + } + } + catch (Exception ex) + { + //we need a logger :( + } + } + + /// + /// Queues an action for invocation on the game thread and optionally runs a callback on completion + /// + /// + /// + /// + public void BeginGameAction(Action action, Action callback = null, object state = null) + { + try + { + if (Thread.CurrentThread == MySandboxGame.Static.UpdateThread) + { + action(); + } + else + { + Task.Run(() => + { + GameAction(action); + callback?.Invoke(state); + }); + } + } + catch (Exception ex) + { + // log + } } private void OnSessionLoading()