瀏覽代碼

修复程序重启造成TCP为完全退出造成的异常

LC 2 月之前
父節點
當前提交
63d9bd55ae
共有 3 個文件被更改,包括 78 次插入36 次删除
  1. 19 10
      App.xaml.cs
  2. 15 14
      Config/Config.json
  3. 44 12
      Core/TcpServerFrame.cs

+ 19 - 10
App.xaml.cs

@@ -95,7 +95,7 @@ namespace SWRIS
                 MessageBox.Show("当前配置的端口已被占用,请更换端口或关闭占用该端口的程序", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                 Environment.Exit(0);
             }
-          
+
             if (Settings.Default.IsDebug)
             {
                 SetAutoStart(false);
@@ -282,17 +282,26 @@ namespace SWRIS
                 }
             }
         }
-        public static void RestartApplication()
+        public static async void RestartApplication()
         {
-            _singleInstanceManager?.Dispose();
-            // 获取当前进程的可执行文件路径
-            string currentExecutablePath = Process.GetCurrentProcess().MainModule.FileName;
-
-            // 启动新进程实例
-            Process.Start(currentExecutablePath);
+            try
+            {
+                _singleInstanceManager?.Dispose();
+                string currentExecutablePath = Process.GetCurrentProcess().MainModule.FileName;
+                // 启动新进程
+                Process.Start(currentExecutablePath);
 
-            // 关闭当前应用程序
-            Current.Shutdown();
+                // 安全关闭
+                Current?.Dispatcher.Invoke(() =>
+                {
+                    Current.Shutdown();
+                });
+            }
+            catch (Exception ex)
+            {
+                // 记录错误日志
+                MessageBox.Show($"重启失败: {ex.Message}");
+            }
         }
         protected override void OnExit(ExitEventArgs e)
         {

+ 15 - 14
Config/Config.json

@@ -2,7 +2,7 @@
   "AppName": "在线式钢丝绳电磁检测系统",
   "Version": "250902",
   "Copyright": "河南恒达机电设备有限公司",
-  "IpAddress": "127.0.0.1",
+  "IpAddress": "192.168.1.233",
   "Port": 9005,
   "DataSaveDays": 120,
   "CleanScheduledTime": "02:00:00",
@@ -51,10 +51,10 @@
   },
   "Equipments": [
     {
-      "RopeNumber": 2,
-      "RopeName": "起升钢丝绳3#",
-      "IpAddress": "192.168.1.127",
-      "SerialNo": "2508001",
+      "RopeNumber": 1,
+      "RopeName": "起升钢丝绳1#",
+      "IpAddress": "192.168.1.241",
+      "SerialNo": "2509001",
       "Supplier": "宁夏恒力",
       "RopeCoreType": 1,
       "WireMaterialType": 1,
@@ -62,7 +62,7 @@
       "LiftHightRatio": 2,
       "LayType": 1,
       "DisableAlarm": false,
-      "InUseSensor": [ 1, 2, 3, 4 ],
+      "InUseSensor": [ 1, 2, 3 ],
       "Parameter": {
         "MainBoardSoftwareVersion": "2.07.01 1.1.0",
         "SensorCount": 4,
@@ -82,7 +82,7 @@
         "SoundLightAlarmAutoResetMode": -1,
         "WireRopeType": 0,
         "WireRopeCount": 1,
-        "WireRopeLength": 32.0,
+        "WireRopeLength": 24,
         "WireRopeDiameter": 20.0,
         "WireRopeStrandCount": 6,
         "WireRopeStrandWireCount": 19,
@@ -92,10 +92,10 @@
       }
     },
     {
-      "RopeNumber": 1,
-      "RopeName": "起升钢丝绳1#",
-      "IpAddress": "192.168.1.241",
-      "SerialNo": "2509001",
+      "RopeNumber": 2,
+      "RopeName": "起升钢丝绳3#",
+      "IpAddress": "192.168.1.127",
+      "SerialNo": "2508001",
       "Supplier": "宁夏恒力",
       "RopeCoreType": 1,
       "WireMaterialType": 1,
@@ -103,7 +103,7 @@
       "LiftHightRatio": 2,
       "LayType": 1,
       "DisableAlarm": false,
-      "InUseSensor": [ 1, 2, 3 ],
+      "InUseSensor": [ 1, 2, 3, 4 ],
       "Parameter": {
         "MainBoardSoftwareVersion": "2.07.01 1.1.0",
         "SensorCount": 4,
@@ -123,7 +123,7 @@
         "SoundLightAlarmAutoResetMode": -1,
         "WireRopeType": 0,
         "WireRopeCount": 1,
-        "WireRopeLength": 24,
+        "WireRopeLength": 32.0,
         "WireRopeDiameter": 20.0,
         "WireRopeStrandCount": 6,
         "WireRopeStrandWireCount": 19,
@@ -132,5 +132,6 @@
         "TwistFactor": 0.0
       }
     }
+
   ]
-}
+}

+ 44 - 12
Core/TcpServerFrame.cs

@@ -14,6 +14,7 @@ using System.Security.Cryptography;
 using System.Text;
 using System.Threading;
 using System.Threading.Tasks;
+using static System.Windows.Forms.AxHost;
 
 namespace SWRIS.Core
 {
@@ -45,6 +46,7 @@ namespace SWRIS.Core
         private readonly ByteTransform byteTransform;
         private const string PASSWORD = "WNDTM4";
         private static ConcurrentDictionary<string, ClientState> _connectedClients;
+        private CancellationTokenSource ctsToken = new CancellationTokenSource();
         public TcpServerFrame(string ipAddress, int port)
         {
             _ipAddress = ipAddress;
@@ -93,8 +95,24 @@ namespace SWRIS.Core
         public void Stop()
         {
             _isRunning = false;
-            _listener.Shutdown(SocketShutdown.Both);
-            _listener?.Close();
+            // 取消心跳检测任务
+            ctsToken?.Cancel();
+            ctsToken?.Dispose();
+            ctsToken = null;
+            // 关闭所有客户端连接
+            foreach (var client in _connectedClients.Values)
+            {
+                SafeCloseClient(client);
+            }
+            _connectedClients.Clear();
+
+            // 关闭监听器
+            if (_listener != null && _listener.Connected)
+            {
+                _listener.Shutdown(SocketShutdown.Both);
+                _listener.Close();
+                _listener = null;
+            }
         }
 
         private void OnClientConnected(IAsyncResult ar)
@@ -126,23 +144,37 @@ namespace SWRIS.Core
         }
         private void StartHeartbeatCheck()
         {
-            ThreadPool.QueueUserWorkItem(act =>
+            ThreadPool.QueueUserWorkItem(async state =>
             {
-                while (_isRunning)
-                {
-                    Thread.Sleep(TimeSpan.FromSeconds(5)); // 每5秒检测一次
+                var token = (CancellationTokenSource)state;
 
-                    foreach (var client in _connectedClients.ToArray())
+                while (_isRunning && !token.IsCancellationRequested)
+                {
+                    try
                     {
-                        if ((DateTime.UtcNow - client.Value.LastActiveTime).TotalSeconds > 15)
+                        await Task.Delay(TimeSpan.FromSeconds(5), token.Token);
+
+                        foreach (var client in _connectedClients.ToArray())
                         {
-                            SafeCloseClient(client.Value);
-                            DebugMessageReceived?.Invoke(this,
-                                new DebugMessageReceivedEventArgs($"心跳超时,强制断开", ipAddress: client.Value.IpAddress));
+                            if ((DateTime.UtcNow - client.Value.LastActiveTime).TotalSeconds > 15)
+                            {
+                                SafeCloseClient(client.Value);
+                                DebugMessageReceived?.Invoke(this,
+                                    new DebugMessageReceivedEventArgs($"心跳超时,强制断开", ipAddress: client.Value.IpAddress));
+                            }
                         }
                     }
+                    catch (TaskCanceledException)
+                    {
+                        // 正常取消,退出循环
+                        break;
+                    }
+                    catch (Exception ex)
+                    {
+                        LogHelper.Error($"心跳检测异常: {ex.Message}", ex);
+                    }
                 }
-            });
+            }, ctsToken);
         }
 
         private async void OnDataReceived(IAsyncResult ar)