Thread termination fix

This commit is contained in:
Sardelka 2022-06-27 15:35:23 +08:00
parent 0800361b40
commit 7670af88a2
2 changed files with 57 additions and 31 deletions

View File

@ -8,7 +8,7 @@ namespace RageCoop.Server
{ {
class Program class Program
{ {
public static bool ReadyToStop = false; private static bool Stopping = false;
static void Main(string[] args) static void Main(string[] args)
{ {
var mainLogger= new Core.Logger() var mainLogger= new Core.Logger()
@ -18,45 +18,45 @@ namespace RageCoop.Server
}; };
try try
{ {
#if DEBUG
new Thread(async () =>
{
do
{
Console.Title = string.Format("RAGECOOP [{0,5:P2}] [{1:F}MB]", await GetCpuUsageForProcess(), Process.GetCurrentProcess().PrivateMemorySize64 * 0.000001);
Thread.Sleep(500);
} while (true);
}).Start();
#else
Console.Title = "RAGECOOP"; Console.Title = "RAGECOOP";
var setting = Util.Read<ServerSettings>("Settings.xml");
#if DEBUG
setting.LogLevel=0;
#endif #endif
var server = new Server(setting, mainLogger);
Console.CancelKeyPress += delegate(object sender, ConsoleCancelEventArgs e) Console.CancelKeyPress += delegate(object sender, ConsoleCancelEventArgs e)
{ {
mainLogger.Info("Initiating shutdown sequence...");
mainLogger.Info("Press Ctrl+C again to commence an emergency shutdown.");
if (e.SpecialKey == ConsoleSpecialKey.ControlC) if (e.SpecialKey == ConsoleSpecialKey.ControlC)
{ {
if (!ReadyToStop) if (!Stopping)
{ {
e.Cancel = true; e.Cancel = true;
ReadyToStop = true; Stopping = true;
server.Stop();
mainLogger.Info("Server stopped.");
mainLogger.Dispose();
Thread.Sleep(3000);
} }
else else
{ {
mainLogger.Flush();
Environment.Exit(1); Environment.Exit(1);
} }
} }
}; };
server.Start();
_ = new Server(Util.Read<ServerSettings>("Settings.xml"), mainLogger); mainLogger?.Info("Please use CTRL + C if you want to stop the server!");
} }
catch (Exception e) catch (Exception e)
{ {
mainLogger.Error(e); mainLogger.Error(e);
mainLogger.Error($"Fatal error occurred, server shutting down."); mainLogger.Error($"Fatal error occurred, server shutting down.");
Thread.Sleep(3000); mainLogger.Flush();
Thread.Sleep(5000);
Environment.Exit(1);
} }
mainLogger.Dispose();
} }
} }
} }

View File

@ -30,6 +30,7 @@ namespace RageCoop.Server
internal BaseScript BaseScript { get; set; }=new BaseScript(); internal BaseScript BaseScript { get; set; }=new BaseScript();
internal readonly ServerSettings Settings; internal readonly ServerSettings Settings;
internal NetServer MainNetServer; internal NetServer MainNetServer;
private bool _stopping=false;
internal readonly Dictionary<Command, Action<CommandContext>> Commands = new(); internal readonly Dictionary<Command, Action<CommandContext>> Commands = new();
internal readonly Dictionary<long,Client> Clients = new(); internal readonly Dictionary<long,Client> Clients = new();
@ -40,6 +41,8 @@ namespace RageCoop.Server
public API API { get; private set; } public API API { get; private set; }
internal Logger Logger; internal Logger Logger;
private Security Security; private Security Security;
private Thread _listenerThread;
private Thread _announceThread;
public Server(ServerSettings settings,Logger logger=null) public Server(ServerSettings settings,Logger logger=null)
{ {
Settings = settings; Settings = settings;
@ -49,6 +52,10 @@ namespace RageCoop.Server
API=new API(this); API=new API(this);
Resources=new Resources(this); Resources=new Resources(this);
Security=new Security(Logger); Security=new Security(Logger);
}
public void Start()
{
Logger?.Info("================"); Logger?.Info("================");
Logger?.Info($"Server bound to: 0.0.0.0:{Settings.Port}"); Logger?.Info($"Server bound to: 0.0.0.0:{Settings.Port}");
Logger?.Info($"Server version: {Assembly.GetCallingAssembly().GetName().Version}"); Logger?.Info($"Server version: {Assembly.GetCallingAssembly().GetName().Version}");
@ -70,7 +77,7 @@ namespace RageCoop.Server
MainNetServer = new NetServer(config); MainNetServer = new NetServer(config);
MainNetServer.Start(); MainNetServer.Start();
SendPlayerTimer.Elapsed+=(s,e) => { SendPlayerInfos(); }; SendPlayerTimer.Elapsed+=(s, e) => { SendPlayerInfos(); };
SendPlayerTimer.AutoReset=true; SendPlayerTimer.AutoReset=true;
SendPlayerTimer.Enabled=true; SendPlayerTimer.Enabled=true;
Logger?.Info(string.Format("Server listening on {0}:{1}", config.LocalAddress.ToString(), config.Port)); Logger?.Info(string.Format("Server listening on {0}:{1}", config.LocalAddress.ToString(), config.Port));
@ -78,7 +85,7 @@ namespace RageCoop.Server
{ {
#region -- MASTERSERVER -- #region -- MASTERSERVER --
new Thread(async () => _announceThread=new Thread(async () =>
{ {
try try
{ {
@ -107,8 +114,8 @@ namespace RageCoop.Server
Logger?.Error(ex.InnerException?.Message ?? ex.Message); Logger?.Error(ex.InnerException?.Message ?? ex.Message);
return; return;
} }
var realMaster = Settings.MasterServer=="[AUTO]" ? Util.DownloadString("https://ragecoop.online/stuff/masterserver") : Settings.MasterServer; var realMaster = Settings.MasterServer=="[AUTO]" ? Util.DownloadString("https://ragecoop.online/stuff/masterserver") : Settings.MasterServer;
while (!Program.ReadyToStop) while (!_stopping)
{ {
string msg = string msg =
"{ " + "{ " +
@ -152,7 +159,17 @@ namespace RageCoop.Server
} }
// Sleep for 10s // Sleep for 10s
Thread.Sleep(10000); for(int i = 0; i<10; i++)
{
if (_stopping)
{
break;
}
else
{
Thread.Sleep(1000);
}
}
} }
} }
catch (HttpRequestException ex) catch (HttpRequestException ex)
@ -163,20 +180,30 @@ namespace RageCoop.Server
{ {
Logger?.Error($"MasterServer: {ex.Message}"); Logger?.Error($"MasterServer: {ex.Message}");
} }
}).Start(); });
_announceThread.Start();
#endregion #endregion
} }
BaseScript.API=API; BaseScript.API=API;
BaseScript.OnStart(); BaseScript.OnStart();
Resources.LoadAll(); Resources.LoadAll();
Listen(); _listenerThread=new Thread(() => Listen());
_listenerThread.Start();
}
public void Stop()
{
_stopping = true;
SendPlayerTimer.Stop();
SendPlayerTimer.Enabled=false;
SendPlayerTimer.Dispose();
Logger?.Flush();
_listenerThread?.Join();
_announceThread?.Join();
} }
private void Listen() private void Listen()
{ {
Logger?.Info("Listening for clients"); Logger?.Info("Listening for clients");
Logger?.Info("Please use CTRL + C if you want to stop the server!"); while (!_stopping)
while (!Program.ReadyToStop)
{ {
try try
{ {
@ -188,9 +215,8 @@ namespace RageCoop.Server
Logger?.Error(ex); Logger?.Error(ex);
} }
} }
Logger?.Warning("Server is shutting down!"); Logger?.Info("Server is shutting down!");
MainNetServer.Shutdown("Server is shutting down!"); MainNetServer.Shutdown("Server is shutting down!");
Logger?.Info("Waiting for resources to stop...Press Ctrl+C again to forcibly terminate the program.");
BaseScript.OnStop(); BaseScript.OnStop();
Resources.StopAll(); Resources.StopAll();
} }