diff --git a/src/ST.Client.Desktop.Avalonia.App/ApplicationInstance.cs b/src/ST.Client.Desktop.Avalonia.App/ApplicationInstance.cs index 2dc6cfb73..2c1c3f0b6 100644 --- a/src/ST.Client.Desktop.Avalonia.App/ApplicationInstance.cs +++ b/src/ST.Client.Desktop.Avalonia.App/ApplicationInstance.cs @@ -1,3 +1,4 @@ +using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.IO.Pipes; @@ -35,7 +36,7 @@ namespace System.Application.UI } } - static bool GetIsFirst() + static IEnumerable GetCurrentAllProcess() { var current = Process.GetCurrentProcess(); var query = from p in Process.GetProcessesByName(current.ProcessName) @@ -46,6 +47,29 @@ namespace System.Application.UI p.MainModule.FileName == current.MainModule.FileName && p.MainModule.ModuleName == current.MainModule.ModuleName)) select p; + return query; + } + + public static bool TryKillCurrentAllProcess() + { + foreach (var p in GetCurrentAllProcess()) + { + try + { + p.Kill(true); + p.WaitForExit(500); + } + catch + { + + } + } + return GetIsFirst(); + } + + static bool GetIsFirst() + { + var query = GetCurrentAllProcess(); var r = query.Any(); return !r; } @@ -97,19 +121,20 @@ namespace System.Application.UI /// 给主进程发送消息 /// /// - public static void SendMessage(string value) + public static bool SendMessage(string value) { var name = GetPipeName(); try { using var pipeClient = new NamedPipeClientStream(".", name, PipeDirection.Out, PipeOptions.None, TokenImpersonationLevel.Impersonation); - pipeClient.Connect(); + pipeClient.Connect(1000); using StreamWriter sw = new StreamWriter(pipeClient); sw.WriteLine(value); + return true; } - catch (IOException) + catch { - + return false; } } diff --git a/src/ST.Client.Desktop.Avalonia.App/CommandLineTools.cs b/src/ST.Client.Desktop.Avalonia.App/CommandLineTools.cs index fbb3a5189..90d72acd6 100644 --- a/src/ST.Client.Desktop.Avalonia.App/CommandLineTools.cs +++ b/src/ST.Client.Desktop.Avalonia.App/CommandLineTools.cs @@ -39,12 +39,29 @@ namespace System.Application.UI #endif if (IsMainProcess) { - appInstance = new ApplicationInstance(); + var isInitAppInstanceReset = false; + initAppInstance: appInstance = new ApplicationInstance(); if (!appInstance.IsFirst) { //Console.WriteLine("ApplicationInstance.SendMessage(string.Empty);"); - ApplicationInstance.SendMessage(string.Empty); - return; + if (ApplicationInstance.SendMessage(string.Empty)) + { + return; + } + else + { + if (!isInitAppInstanceReset && + ApplicationInstance.TryKillCurrentAllProcess()) + { + isInitAppInstanceReset = true; + appInstance.Dispose(); + goto initAppInstance; + } + else + { + return; + } + } } appInstance.MessageReceived += value => {