diff --git a/UIShare/GlobalVariable/DeviceHealthMonitor.cs b/UIShare/GlobalVariable/DeviceHealthMonitor.cs index 573610e..b95d497 100644 --- a/UIShare/GlobalVariable/DeviceHealthMonitor.cs +++ b/UIShare/GlobalVariable/DeviceHealthMonitor.cs @@ -7,6 +7,7 @@ using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; +using System.Windows; namespace UIShare.GlobalVariable { @@ -221,17 +222,27 @@ namespace UIShare.GlobalVariable } /// - /// 同步更新 SystemConfig.DeviceList 中对应设备的 IsConnected 状态(驱动 UI 刷新) + /// 通过 UI 线程更新 SystemConfig.DeviceList 中对应设备的 IsConnected 状态(驱动 UI 刷新)。 + /// Timer 回调运行在线程池线程上,必须切回 UI 线程才能触发 PropertyChanged。 /// private void UpdateDeviceInfoState(string deviceName, bool isConnected) { var info = _systemConfig?.DeviceList? .FirstOrDefault(d => d != null && string.Equals(d.DeviceName, deviceName, StringComparison.OrdinalIgnoreCase)); - if (info != null) + if (info == null) return; + + var dispatcher = Application.Current?.Dispatcher; + if (dispatcher == null || dispatcher.CheckAccess()) { + // 已在 UI 线程(或无 Dispatcher),直接赋值 info.IsConnected = isConnected; } + else + { + // 切回 UI 线程赋值,避免跨线程 PropertyChanged 异常 + dispatcher.BeginInvoke(() => info.IsConnected = isConnected); + } } public void Dispose()