U:修改PLC监听数据不会更新BUG

This commit is contained in:
jimmy committed 2025-12-10 13:37:04 +08:00
1 parent d9e5a5483c
commit 6ed0d3f1c2
2 files changed
+28 -15

No files matched your search

+18 -15
View File
@@ -50,7 +50,7 @@ public class PlcViewModel : ViewModelBase
ReadCommand = new AsyncCommand(ReadAsync); ReadCommand = new AsyncCommand(ReadAsync);
WriteCommand = new AsyncCommand(WriteAsync); WriteCommand = new AsyncCommand(WriteAsync);
AddMonitorCommand = new RelayCommand(AddMonitor); AddMonitorCommand = new RelayCommand(AddMonitor);
RemoveMonitorCommand = new RelayCommand<PlcTag>(RemoveMonitor, tag => tag != null); RemoveMonitorCommand = new RelayCommand<PlcTagViewModel>(RemoveMonitor, tag => tag != null);
} }
#region Properties #region Properties
@@ -120,7 +120,7 @@ public class PlcViewModel : ViewModelBase
// 数据源 // 数据源
public ObservableCollection<PlcBrand> Brands { get; } = new(Enum.GetValues<PlcBrand>()); public ObservableCollection<PlcBrand> Brands { get; } = new(Enum.GetValues<PlcBrand>());
public ObservableCollection<CpuType> CpuTypes { get; } = new(Enum.GetValues<CpuType>()); public ObservableCollection<CpuType> CpuTypes { get; } = new(Enum.GetValues<CpuType>());
public ObservableCollection<PlcTag> MonitoredTags { get; } = new(); public ObservableCollection<PlcTagViewModel> MonitoredTags { get; } = new();
#endregion #endregion
@@ -206,15 +206,18 @@ public class PlcViewModel : ViewModelBase
var tag = new PlcTag var tag = new PlcTag
{ {
Address = MonitorAddress, Address = MonitorAddress,
DataType = typeof(short), DataType = typeof(short)
OnChanged = (t, v) => };
var vm = new PlcTagViewModel(tag);
tag.OnChanged = (t, v) =>
{
// 使用Dispatcher在UI线程更新值,避免跨线程访问异常
_dispatcher.InvokeAsync(() =>
{ {
// 使用Dispatcher在UI线程更新值,避免跨线程访问异常 vm.UpdateValue();
_dispatcher.InvokeAsync(() => });
{
t.Value = v;
});
}
}; };
_plcService.Subscribe(tag); _plcService.Subscribe(tag);
@@ -222,21 +225,21 @@ public class PlcViewModel : ViewModelBase
// 在UI线程添加到集合 // 在UI线程添加到集合
_dispatcher.InvokeAsync(() => _dispatcher.InvokeAsync(() =>
{ {
MonitoredTags.Add(tag); MonitoredTags.Add(vm);
}); });
} }
private void RemoveMonitor(PlcTag? tag) private void RemoveMonitor(PlcTagViewModel? tagVm)
{ {
if (tag == null) return; if (tagVm == null) return;
// 从PLC服务取消订阅 // 从PLC服务取消订阅
_plcService.Unsubscribe(tag.Id); _plcService.Unsubscribe(tagVm.Id);
// 从UI集合移除 // 从UI集合移除
_dispatcher.InvokeAsync(() => _dispatcher.InvokeAsync(() =>
{ {
MonitoredTags.Remove(tag); MonitoredTags.Remove(tagVm);
}); });
} }
} }
@@ -73,6 +73,16 @@ public class PlcMonitorService : IPlcService, IDisposable
{ {
_logger?.LogDebug("Monitor task cancelled successfully"); _logger?.LogDebug("Monitor task cancelled successfully");
} }
finally
{
_monitorTask = null;
}
}
if (_cts != null)
{
_cts.Dispose();
_cts = null;
} }
await _driver.DisconnectAsync(); await _driver.DisconnectAsync();