From 5ae58e6a980f0d21ca8f11dad2492840262bcaab Mon Sep 17 00:00:00 2001
From: 2dust <31833384+2dust@users.noreply.github.com>
Date: Tue, 14 Jan 2025 14:49:17 +0800
Subject: [PATCH] Improve reload function

---
 v2rayN/ServiceLib/Handler/CoreHandler.cs      | 25 ++++++-------------
 .../ViewModels/MainWindowViewModel.cs         | 24 ++++++++++--------
 2 files changed, 21 insertions(+), 28 deletions(-)

diff --git a/v2rayN/ServiceLib/Handler/CoreHandler.cs b/v2rayN/ServiceLib/Handler/CoreHandler.cs
index a4922af7..ddc890d8 100644
--- a/v2rayN/ServiceLib/Handler/CoreHandler.cs
+++ b/v2rayN/ServiceLib/Handler/CoreHandler.cs
@@ -67,13 +67,17 @@ namespace ServiceLib.Handler
                 return;
             }
 
-            UpdateFunc(true, $"{node.GetSummary()}");
+            UpdateFunc(false, $"{node.GetSummary()}");
             UpdateFunc(false, $"{Utils.GetRuntimeInfo()}");
             UpdateFunc(false, string.Format(ResUI.StartService, DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")));
             await CoreStop();
             await Task.Delay(100);
             await CoreStart(node);
             await CoreStartPreService(node);
+            if (_process != null)
+            {
+                UpdateFunc(true, $"{node.GetSummary()}");
+            }
         }
 
         public async Task<int> LoadCoreConfigSpeedtest(List<ServerTestItem> selecteds)
@@ -220,8 +224,6 @@ namespace ServiceLib.Handler
                     await RunProcessAsLinuxSudo(proc, fileName, coreInfo, configPath);
                 }
 
-                var startUpErrorMessage = new StringBuilder();
-                var startUpSuccessful = false;
                 if (displayLog)
                 {
                     proc.OutputDataReceived += (sender, e) =>
@@ -233,11 +235,6 @@ namespace ServiceLib.Handler
                     {
                         if (Utils.IsNullOrEmpty(e.Data)) return;
                         UpdateFunc(false, e.Data + Environment.NewLine);
-
-                        if (!startUpSuccessful)
-                        {
-                            startUpErrorMessage.Append(e.Data + Environment.NewLine);
-                        }
                     };
                 }
                 proc.Start();
@@ -258,18 +255,12 @@ namespace ServiceLib.Handler
                     proc.BeginErrorReadLine();
                 }
 
+                await Task.Delay(500);
                 AppHandler.Instance.AddProcess(proc.Handle);
-                if (proc.WaitForExit(1000))
+                if (proc is null or { HasExited: true })
                 {
-                    proc.CancelErrorRead();
-                    throw new Exception(displayLog ? startUpErrorMessage.ToString() : "启动进程失败并退出 (Failed to start the process and exited)");
+                    throw new Exception(ResUI.FailedToRunCore);
                 }
-                else
-                {
-                    startUpSuccessful = true;
-                }
-
-                AppHandler.Instance.AddProcess(proc.Handle);
                 return proc;
             }
             catch (Exception ex)
diff --git a/v2rayN/ServiceLib/ViewModels/MainWindowViewModel.cs b/v2rayN/ServiceLib/ViewModels/MainWindowViewModel.cs
index 3d569d4e..b4542b2a 100644
--- a/v2rayN/ServiceLib/ViewModels/MainWindowViewModel.cs
+++ b/v2rayN/ServiceLib/ViewModels/MainWindowViewModel.cs
@@ -222,6 +222,7 @@ namespace ServiceLib.ViewModels
                 await StatisticsHandler.Instance.Init(_config, UpdateStatisticsHandler);
             }
 
+            BlReloadEnabled = true;
             await Reload();
             await AutoHideStartup();
             Locator.Current.GetService<StatusBarViewModel>()?.RefreshRoutingsMenu();
@@ -533,8 +534,17 @@ namespace ServiceLib.ViewModels
 
         #region core job
 
-        public async Task Reload()
+        public async Task Reload(int times = 0)
         {
+            //If there are unfinished reload job, wait a few seconds and exec again.
+            if (!BlReloadEnabled)
+            {
+                await Task.Delay(3000);
+                if (times > 3) return;
+                await Reload(++times);
+                return;
+            }
+
             BlReloadEnabled = false;
 
             await LoadCore();
@@ -558,16 +568,8 @@ namespace ServiceLib.ViewModels
 
         private async Task LoadCore()
         {
-            //if (_config.tunModeItem.enableTun)
-            //{
-            //    Task.Delay(1000).Wait();
-            //    WindowsUtils.RemoveTunDevice();
-            //}
-            await Task.Run(async () =>
-            {
-                var node = await ConfigHandler.GetDefaultServer(_config);
-                await CoreHandler.Instance.LoadCore(node);
-            });
+            var node = await ConfigHandler.GetDefaultServer(_config);
+            await CoreHandler.Instance.LoadCore(node);
         }
 
         public async Task CloseCore()