I’m trying to create an effiecent way to shut down my console application. To do this I have a while loop in my program’s main method waiting for a request to shutdown.
var rebootAfterClose = false; while (true) { var input = Console.ReadKey(); if (input.Key == ConsoleKey.C && input.Modifiers == ConsoleModifiers.Control) { break; } if (input.Key != ConsoleKey.R || input.Modifiers != ConsoleModifiers.Control) { continue; } rebootAfterClose = true; break; } Server?.Stop(rebootAfterClose);
I then have these methods, the stop is the one that gets called, Dispose gets called in Stop().
public void Dispose() { if (Disposing) { return; } Disposing = true; BaseHandler.PlayerHandler.Dispose(); ConsoleUpdater.Dispose(); SocketHandler.Dispose(); } public void Stop(bool restart) { Task.Factory.StartNew(() => { var shutdownMessage = PlusEnvironment.GetLanguageManager().TryGetValue("server.shutdown.message"); var shutdownPacket = new BroadcastMessageAlertComposer(shutdownMessage); Program.Server.BaseHandler.PlayerHandler.SendPacketToPlayers(shutdownPacket); ConsoleUpdater.Stop(); Console.Clear(); Console.WriteLine(); Console.Title = "Stopping..."; Logger.Warn("Server is " + (restart ? "rebooting" : "shutting down") + "...."); Thread.Sleep(5000); // not sure if I should use this instead? : Task.Delay(5000); Dispose(); if (restart) { Process.Start(Assembly.GetExecutingAssembly().Location); } Environment.Exit(0); }); }
I used a thread as I didn’t want to block the thread with the 5 second delay. I’m currently looking to just tidy this mechanism up as I am really new to multithreading and just want to know if I did okay, I appreciate everyone who contributes a comment or answer.
Another thing I’m worried about is the while (true) loop in my main method, is there any better way to do this? I need to avoid closing the console application on any other key other than the ones in the while loop (CTRL&C, or CTRL&R) but I can’t think of a better way to do that.