From d2c8c8d3cdfdd5e34b18a026e35c5e188bf16ede Mon Sep 17 00:00:00 2001 From: TheUbMunster <66451362+TheUbMunster@users.noreply.github.com> Date: Thu, 28 Jul 2022 00:11:40 -0600 Subject: [PATCH] Fixed race condition with restart to make sure it only happens after the listener closes. --- Server/Program.cs | 22 +++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/Server/Program.cs b/Server/Program.cs index 72a24a7..57b6ef9 100644 --- a/Server/Program.cs +++ b/Server/Program.cs @@ -11,6 +11,7 @@ using Timer = System.Timers.Timer; Server.Server server = new Server.Server(); HashSet shineBag = new HashSet(); CancellationTokenSource cts = new CancellationTokenSource(); +bool restartRequested = false; Task listenTask = server.Listen(cts.Token); Logger consoleLogger = new Logger("Console"); DiscordBot bot = new DiscordBot(); @@ -551,12 +552,7 @@ CommandHandler.RegisterCommand("restartserver", args => else { consoleLogger.Info("Received restartserver command"); - string? path = System.Reflection.Assembly.GetEntryAssembly()?.GetName().Name; - const string unableToStartMsg = "Unable to ascertain the executable location, you'll need to re-run the server manually."; - if (path != null) - Console.WriteLine($"Running: {System.Diagnostics.Process.Start(path)?.Id.ToString() ?? unableToStartMsg}"); - else - consoleLogger.Info(unableToStartMsg); + restartRequested = true; cts.Cancel(); return "restarting..."; } @@ -585,4 +581,16 @@ Task.Run(() => { } }); -await listenTask; \ No newline at end of file +await listenTask; +if (restartRequested) //need to do this here because this needs to happen after the listener closes, and there isn't an + //easy way to sync in the restartserver command without it exiting Main() +{ + string? path = System.Reflection.Assembly.GetEntryAssembly()?.GetName().Name; + const string unableToStartMsg = "Unable to ascertain the executable location, you'll need to re-run the server manually."; + if (path != null) //path is probably just "Server", but in the context of the assembly, that's all you need to restart it. + { + Console.WriteLine($"Running (pid): {System.Diagnostics.Process.Start(path)?.Id.ToString() ?? unableToStartMsg}"); + } + else + consoleLogger.Info(unableToStartMsg); +} \ No newline at end of file