plcsharp/PLCSharpWpf/VVMs/Workflows/Workflow.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

399 lines
11 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using PLCSharp.Core.Prism;
using PLCSharp.Core.Common;
using PLCSharp.Models;
using Prism.Commands;
using Prism.Mvvm;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Diagnostics;
using System.Reflection;
using System.Threading;
namespace PLCSharp.VVMs.Workflows
{
/// <summary>
/// 工作流
/// </summary>
public class Workflow : BindableBase
{
/// <summary>
/// 唯一标识
/// </summary>
[Key]
public Guid ID { get; set; } = Guid.NewGuid();
/// <summary>
/// 配方标识
/// </summary>
public Guid RecipeID { get; set; }
private string _Name;
/// <summary>
/// 配置项
/// </summary>
public string Name
{
get { return _Name; }
set
{
if (_Name != value)
{
Prompt = "已修改,请保存";
}
SetProperty(ref _Name, value);
}
}
private string _Prompt;
/// <summary>
/// 提示
/// </summary>
[NotMapped]
public string Prompt
{
get { return _Prompt; }
set { SetProperty(ref _Prompt, value); }
}
private double _CycleDelayTime = 0.01;
/// <summary>
/// 循环结束延迟
/// </summary>
public double CycleDelayTime
{
get { return _CycleDelayTime; }
set
{
if (_CycleDelayTime != value)
{
Prompt = "已修改,请保存";
}
SetProperty(ref _CycleDelayTime, value);
}
}
private string _Code;
private double _CycleTime;
/// <summary>
/// CycleTime
/// </summary>
[NotMapped]
public double CycleTime
{
get { return _CycleTime; }
set { SetProperty(ref _CycleTime, value); }
}
/// <summary>
/// 配置项
/// </summary>
public string Code
{
get { return _Code; }
set
{
if (_Code != value)
{
IsCompiled = false;
Prompt = "已修改,请编译";
}
SetProperty(ref _Code, value);
}
}
private string _Comment;
/// <summary>
/// 备注
/// </summary>
public string Comment
{
get { return _Comment; }
set
{
if (_Comment != value)
{
Prompt = "已修改,请保存";
}
SetProperty(ref _Comment, value);
}
}
private bool _AutomaticExecution;
/// <summary>
/// 脚本自动运行
/// </summary>
public bool AutomaticExecution
{
get { return _AutomaticExecution; }
set
{
if (_AutomaticExecution != value)
{
Prompt = "已修改,请保存";
}
SetProperty(ref _AutomaticExecution, value);
}
}
/// <summary>
/// 编译时间
/// </summary>
[NotMapped]
public DateTime CompiledTime { get; set; } = DateTime.Now;
private bool _IsCompiled;
/// <summary>
/// IsCompiled
/// </summary>
[NotMapped]
public bool IsCompiled
{
get { return _IsCompiled; }
set { SetProperty(ref _IsCompiled, value); }
}
private bool _IsRuning;
/// <summary>
/// IsRuning
/// </summary>
[NotMapped]
public bool IsRuning
{
get { return _IsRuning; }
set { SetProperty(ref _IsRuning, value); }
}
/// <summary>
/// Assembly
/// </summary>
[NotMapped]
public Assembly Assembly { get; set; }
private string _DebugLog;
/// <summary>
/// Debug日志
/// </summary>
[NotMapped]
public string DebugLog
{
get { return _DebugLog; }
set { SetProperty(ref _DebugLog, value); }
}
private bool _Exception;
/// <summary>
/// 异常
/// </summary>
[NotMapped]
public bool Exception
{
get { return _Exception; }
set { SetProperty(ref _Exception, value); }
}
private AssemblyCSharpBuilder AssemblyCSharpBuilder;
private NatashaLoadContext _loadContext;
private DelegateCommand _Compile;
/// <summary>
/// 编译
/// </summary>
public DelegateCommand Compile =>
_Compile ??= new DelegateCommand(ExecuteCompile);
private void ExecuteCompile()
{
lock (this)
{
try
{
if (IsRuning)
{
DebugLog += "正在运行中,请先停止后再编译。\n";
return;
}
Flow.Reset();
// 卸载上一次编译的动态程序集域,避免每次编译的程序集永久驻留内存(无法被 GC 回收)
UnloadDomain();
// 新建可卸载的加载上下文(域),编译产物加载进该域,下次编译时可整体卸载
_loadContext = NatashaManagement.CreateRandomDomain();
AssemblyCSharpBuilder = new();
AssemblyCSharpBuilder.LoadContext = _loadContext;
// 新域没有 Preheating 预热的内存引用,合并主域(默认域)引用保证脚本能引用 PLCSharp 类型
AssemblyCSharpBuilder.WithCombineReferences(item => item.UseAllReferences());
DebugLog = "编译中,请稍等。\n";
AssemblyCSharpBuilder.ConfigLoadContext(ctx => ctx.AddReferenceAndUsingCode<object>());
AssemblyCSharpBuilder.Add(Code);
AssemblyCSharpBuilder.LogCompilationEvent += OnCompilationLog;
Assembly = AssemblyCSharpBuilder.GetAssembly();
DebugLog += "编译完成。\n";
Prompt = "";
IsCompiled = true;
Exception = false;
var typeName = "Extension_" + ID.ToString().Replace("-", "");
var extType = Assembly.GetTypes().FirstOrDefault(t => t.Name == typeName || t.FullName == typeName);
if (extType != null)
{
var instance = Activator.CreateInstance(extType)!;
action = Assembly.GetDelegateFromShortName<Action<GlobalModel, FlowModel>>(typeName, "Run", target: instance);
}
else
{
DebugLog += "编译错误:无法找到 Extension 类型。\n";
}
}
catch (Exception e)
{
IsCompiled = false;
Exception = true;
DebugLog += e.Message;
}
}
}
/// <summary>
/// 卸载动态程序集域
/// </summary>
private void UnloadDomain()
{
// 先释放对旧程序集的所有强引用,否则 AssemblyLoadContext 无法真正卸载
action = null;
Assembly = null;
AssemblyCSharpBuilder = null;
_loadContext?.Dispose();
_loadContext = null;
}
/// <summary>
/// 编译日志
/// </summary>
private void OnCompilationLog(NatashaCompilationLog log)
{
DebugLog += log.ToString();
}
private Action<GlobalModel, FlowModel> action;
/// <summary>
/// 运行
/// </summary>
/// <param name="globalModel">全局模型</param>
public void Run(GlobalModel globalModel)
{
if (Assembly == null || !IsCompiled || Exception)
{
IsRuning = false;
return;
}
//刚编译完成的脚本,延迟3秒运行,避免编译后立即运行导致的异常
if (CompiledTime.AddSeconds(3) > DateTime.Now) return;
try
{
IsRuning = true;
action?.Invoke(globalModel, Flow);
}
catch (Exception ex)
{
Exception = true;
IsRuning = false;
DebugLog += $"运行时异常: {ex}\n";
globalModel.SendErr($"运行时异常: {ex}\n");
}
}
private BackgroundWorker _BackgroundWorker;
/// <summary>
/// 启动
/// </summary>
/// <param name="globalModel">全局模型</param>
public void Start(GlobalModel globalModel)
{
GlobalModel = globalModel;
_BackgroundWorker = WorkerGuard.Watch(new BackgroundWorker { WorkerSupportsCancellation = true }, "工艺流程扫描");
_BackgroundWorker.DoWork += BackgroundWork;
_BackgroundWorker.RunWorkerAsync();
}
/// <summary>
/// 停止
/// </summary>
public void Stop()
{
while (_BackgroundWorker != null && !_BackgroundWorker.CancellationPending)
{
_BackgroundWorker.CancelAsync();
Thread.Sleep(0);
}
IsRuning = false;
}
private void BackgroundWork(object sender, DoWorkEventArgs e)
{
var worker = (BackgroundWorker)sender;
var sw = Stopwatch.StartNew();
while (!worker.CancellationPending)
{
sw.Restart();
Thread.Sleep((int)(CycleDelayTime * 1000));
if (AutomaticExecution)
{
Run(GlobalModel);
}
else
{
IsRuning = false;
}
sw.Stop();
if (!AutomaticExecution)
{
Thread.Sleep(1000);
}
CycleTime = sw.Elapsed.TotalSeconds;
if (Exception)
{
GlobalModel.ModeState.Sc.Stop = true;
}
}
}
private GlobalModel GlobalModel;
private FlowModel _Flow = new();
/// <summary>
/// 流程状态模型
/// </summary>
[NotMapped]
public FlowModel Flow
{
get { return _Flow; }
set { SetProperty(ref _Flow, value); }
}
}
}