P3: DeviceHealthMonitor 更新 DeviceInfoVM.IsConnected 改用 Dispatcher.BeginInvoke 切回UI线程
This commit is contained in:
@@ -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
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 同步更新 SystemConfig.DeviceList 中对应设备的 IsConnected 状态(驱动 UI 刷新)
|
||||
/// 通过 UI 线程更新 SystemConfig.DeviceList 中对应设备的 IsConnected 状态(驱动 UI 刷新)。
|
||||
/// <para>Timer 回调运行在线程池线程上,必须切回 UI 线程才能触发 PropertyChanged。</para>
|
||||
/// </summary>
|
||||
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()
|
||||
|
||||
Reference in New Issue
Block a user