plcsharp/PLCSharpWpf/Models/GlobalModel.cs
tfarcraw b97083f556 修复异常被静默吞掉:补 UI 线程兜底 + 给 17 个轮询线程装上异常报警
两条异常「消失」的路径:
1) App.RegisterEvents 只挂了 TaskScheduler.UnobservedTaskException 与 AppDomain.UnhandledException,
   全项目没有 Application.DispatcherUnhandledException。WPF UI 线程里的异常(视觉 handler 里 33 处
   Dispatcher.Invoke 委托内部抛出即属此类)会直接让进程闪退,只留一行日志。
2) 17 个 BackgroundWorker 轮询线程全都只订阅 DoWork。BackgroundWorker 会捕获 DoWork 的异常并放进
   RunWorkerCompletedEventArgs.Error,没人订阅就等于吞掉:while(!CancellationPending) 循环直接退出,
   轴/IO/通讯/机器人/气缸的扫描从此不再刷新,而界面看起来一切正常 —— 对上位机这是最危险的失败模式。

改法:
- 新增 Core/Prism/WorkerGuard:Watch(worker, 用途名) 给 worker 挂上「因异常结束就必须上报」的兜底,
  上报出口由启动时 SetFaultSink 注入(Core 层不依赖 App);正常取消(e.Error==null)不算故障,不上报;
  上报通道自身异常被吞掉,兜底逻辑不成为新的崩溃源。
- App.xaml.cs:注册 DispatcherUnhandledException —— 记录日志 + 走统一 errLog 报警通道 + Handled=true
  让进程继续存活(设备运行中闪退比界面某处出错危险得多);OutOfMemoryException 不拦截,交回运行时终止;
  ReportError 带重入保护,避免「报警通道自己出错」造成无限递归。errLog 通道此前只有 ModelBase 在用。
- 17 个 new BackgroundWorker 构造处统一包成 WorkerGuard.Watch(...),并给每个轮询起了中文名(报警里能看出是谁死了)。
- 顺带删掉 App.xaml.cs 里一处没有配对 disable 的孤立 #pragma warning restore VSTHRD200。

新增 5 个 WorkerGuard 回归测试(异常上报内容 / 正常结束不上报 / 正常取消不上报 / 出口抛异常不外泄 / null 参数)。构建 0 error,测试 54/54 通过。
2026-11-17 23:21:05 +08:00

257 lines
8.0 KiB
C#

using PLCSharp.Core.Prism;
using PLCSharp.Core.Tools;
using PLCSharp.VVMs.Connects;
using PLCSharp.VVMs.Cylinders;
using PLCSharp.VVMs.GlobalVariables;
using PLCSharp.VVMs.ModeState;
using PLCSharp.VVMs.MotionController;
using PLCSharp.VVMs.Recipe;
using PLCSharp.VVMs.Robots;
using PLCSharp.VVMs.Vision;
using PLCSharp.VVMs.Workflows;
using Prism.Dialogs;
using Prism.Events;
using Prism.Ioc;
using System.ComponentModel;
using System.Windows;
namespace PLCSharp.Models
{
/// <summary>
/// 全局模型
/// </summary>
[Model]
public partial class GlobalModel : ModelBase
{
/// <summary>
/// 全局模型
/// </summary>
public GlobalModel(IContainerExtension container, IEventAggregator ea, IDialogService dialogService) : base(container, ea, dialogService)
{
NatashaManagement
//获取链式构造器
.GetInitializer()
//使用引用程序集中的命名空间
.WithMemoryUsing()
//使用内存中的元数据
.WithMemoryReference()
//注册域构造器
.Preheating<NatashaDomainCreator>();
foreach (var item in _DatasContext.Recipes)
{
Recipes.Add(item.DeepCopy());
}
if (Recipes.Count == 0)
{
var recipe = new Recipe
{
Name = "First",
Comment = "",
Prompt = "默认配方",
Current = true
};
Recipes.Add(recipe);
RecipeSelected = recipe;
ExecuteRecipeManage("Save");
CurrentRecipe = recipe;
}
else
{
CurrentRecipe = Recipes.Where(r => r.Current).FirstOrDefault();
if (CurrentRecipe == null)
{
CurrentRecipe = Recipes.FirstOrDefault();
CurrentRecipe.Current = true;
RecipeSelected = CurrentRecipe;
ExecuteRecipeManage("Save");
}
RecipeSelected ??= CurrentRecipe;
}
VariablesModel = container.Resolve<VariablesModel>();
VariablesModel.Init(this);
Connects = container.Resolve<ConnectsModel>();
ControllersModel = container.Resolve<ControllersModel>();
ControllersModel.Init(this);
WorkflowsModel = container.Resolve<WorkflowsModel>();
VisionsModel = container.Resolve<VisionsModel>();
RobotModel = container.Resolve<RobotModel>();
VisionsModel.Init(this);
RobotModel.Init(this);
CylindersModel = container.Resolve<CylinderModel>();
CylindersModel.Init(this);
bkgWorker = WorkerGuard.Watch(new BackgroundWorker { WorkerSupportsCancellation = true }, "全局模型状态扫描");
bkgWorker.DoWork += BackgroundWork;
bkgWorker.RunWorkerAsync();
//注册发送给errLog的消息
ea.GetEvent<MessageEvent>().Subscribe(
ErrMessageReceived,
ThreadOption.UIThread,
false,
(filter) => filter.Target.Contains("errLog"));
//注册配方变更
ea.GetEvent<MessageEvent>().Subscribe(
RecipeChanged,
ThreadOption.UIThread,
false,
(filter) => filter.Target.Contains("RecipeChanged"));
//注册退出
ea.GetEvent<MessageEvent>().Subscribe(
Exit,
ThreadOption.UIThread,
false,
(filter) => filter.Target.Contains("Exit"));
}
private void Exit(Message message)
{
if (ModeState.State.Execute)
{
SendInfoDialog("无法退出,请先停止运行!");
return;
}
MessageBoxResult result = MessageBox.Show("确认退出吗?请确保安全!", "提示", MessageBoxButton.OKCancel, MessageBoxImage.Warning);
if (result == MessageBoxResult.OK)
{
// 用户点击了“确定”按钮
MessageBoxResult resultSeconnd = MessageBox.Show("确认退出吗?即将退出控制!", "提示", MessageBoxButton.OKCancel, MessageBoxImage.Warning);
if (resultSeconnd == MessageBoxResult.OK)
{
Application.Current.Shutdown();
}
}
}
#region 全局变量
/// <summary>
/// 获取变量
/// </summary>
/// <param name="name">名称</param>
/// <returns>返回结果</returns>
public Variable GetVariable(string name)
{
var variable = VariablesModel.Variables.FirstOrDefault(v => v.Name == name)
?? throw new Exception("全局变量未配置!");
return variable;
}
#endregion 全局变量
#region 硬件
/// <summary>
/// 连接模型
/// </summary>
public ConnectsModel Connects { get; set; }
/// <summary>
/// Controllers模型
/// </summary>
public ControllersModel ControllersModel { get; set; }
/// <summary>
/// 机器人模型
/// </summary>
public RobotModel RobotModel { get; set; }
/// <summary>
/// 气缸模型
/// </summary>
public CylinderModel CylindersModel { get; set; }
/// <summary>
/// 全局变量
/// </summary>
public VariablesModel VariablesModel { get; set; }
/// <summary>
/// 获取连接
/// </summary>
/// <param name="name">名称</param>
/// <returns>返回结果</returns>
public Connect GetConnect(string name)
{
var connect = Connects.Connects.FirstOrDefault(c => c.Name == name)
?? throw new Exception("网络未配置!");
return connect;
}
/// <summary>
/// 获取Robot
/// </summary>
/// <param name="name">名称</param>
/// <returns>返回结果</returns>
public Robot GetRobot(string name)
{
var robot = RobotModel.Robots.FirstOrDefault(c => c.Name == name)
?? throw new Exception("Robot未配置!");
return robot;
}
/// <summary>
/// 获取VisionFunction
/// </summary>
/// <param name="name">名称</param>
/// <returns>返回结果</returns>
public VisionFunction GetVisionFunction(string name)
{
return VisionsModel.VisionFunctions.FirstOrDefault(v => v.Name == name)
?? throw new Exception("视觉功能未配置!");
}
/// <summary>
/// 获取图像数据
/// </summary>
/// <param name="name">名称</param>
/// <returns>返回结果</returns>
public ImageData GetImageData(string name)
{
var imageData = VisionsModel.ImageDatas.FirstOrDefault(v => v.Name == name)
?? throw new Exception("全局图像未配置!");
if (imageData.Mat == null) throw new Exception("全局图像未赋值!");
return imageData;
}
#endregion 硬件
#region 任务
/// <summary>
/// Workflows模型
/// </summary>
public WorkflowsModel WorkflowsModel { get; set; }
/// <summary>
/// 视觉模型
/// </summary>
public VisionsModel VisionsModel { get; set; }
/// <summary>
/// 获取Task
/// </summary>
/// <param name="name">名称</param>
/// <returns>返回结果</returns>
public Workflow GetTask(string name)
{
return WorkflowsModel.Workflows.FirstOrDefault(t => t.Name == name);
}
#endregion 任务
}
}