From 5c022bfd268928f6fbcfbafa2a3802d45609c269 Mon Sep 17 00:00:00 2001 From: wanglei Date: Sat, 5 Dec 2026 20:01:10 +0800 Subject: [PATCH] =?UTF-8?q?=E5=88=87=E6=8D=A2=E9=85=8D=E6=96=B9=E5=89=8D?= =?UTF-8?q?=E7=AD=89=E5=BE=85=E6=97=A7=E5=B7=A5=E4=BD=9C=E6=B5=81=E9=80=80?= =?UTF-8?q?=E5=87=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- PLCSharpWpf/Models/GlobalModel.Recipes.cs | 65 ++++----- PLCSharpWpf/Properties/AssemblyInfo.cs | 3 +- PLCSharpWpf/VVMs/Workflows/Workflow.cs | 132 ++++++++++-------- PLCSharpWpf/VVMs/Workflows/WorkflowsModel.cs | 56 ++++++-- .../PLCSharp.Tests/WorkflowRegressionTests.cs | 93 ++++++++++++ 5 files changed, 243 insertions(+), 106 deletions(-) create mode 100644 Tests/PLCSharp.Tests/WorkflowRegressionTests.cs diff --git a/PLCSharpWpf/Models/GlobalModel.Recipes.cs b/PLCSharpWpf/Models/GlobalModel.Recipes.cs index d6b654c..32b6695 100644 --- a/PLCSharpWpf/Models/GlobalModel.Recipes.cs +++ b/PLCSharpWpf/Models/GlobalModel.Recipes.cs @@ -71,6 +71,7 @@ namespace PLCSharp.Models private void ExecuteRecipeManage(string cmd) { + if (WorkflowsModel?.IsChangingRecipe == true) return; if (ModeState.State.Execute) { SendInfoDialog($"无法在运行状态操作配方,请先停止"); @@ -178,31 +179,11 @@ namespace PLCSharp.Models if (System.Windows.MessageBox.Show($"确认切换配方 [{RecipeSelected.Name}]?", "确认切换", MessageBoxButton.YesNo, MessageBoxImage.Warning) != MessageBoxResult.Yes) break; - foreach (var item in _DatasContext.Recipes) - { - item.Current = false; - } - foreach (var item in Recipes) - { - item.Current = false; - } - var current = _DatasContext.Recipes.Where(r => r.ID == RecipeSelected.ID).FirstOrDefault(); - if (current != null) - { - current.Current = true; - var uiCurrent = Recipes.FirstOrDefault(r => r.ID == RecipeSelected.ID); - if (uiCurrent != null) uiCurrent.Current = true; - if (current != CurrentRecipe) - { - CurrentRecipe = current; + var selectedId = RecipeSelected.ID; + var current = _DatasContext.Recipes.FirstOrDefault(r => r.ID == selectedId); + if (current == null) break; - SendInfoDialog($"切换到配方:{CurrentRecipe.Name}"); - _EventAggregator.GetEvent().Publish(new() - { - Target = "RecipeChanged" - }); - } - } + _ = ReloadRecipeAsync(current); } break; @@ -809,20 +790,36 @@ namespace PLCSharp.Models #endregion 配方管理 - private void RecipeChanged(Message message) - { - //结束当前配方的任务 + private void RecipeChanged(Message message) => _ = ReloadRecipeAsync(); - foreach (var item in WorkflowsModel.Workflows) + private async Task ReloadRecipeAsync(Recipe selected = null) + { + try { - try + await WorkflowsModel.ChangeRecipeAsync(() => { - item.Stop(); - } - catch (Exception) - { - } + if (selected != null) + { + foreach (var item in _DatasContext.Recipes) + item.Current = item.ID == selected.ID; + _DatasContext.Save(); + foreach (var item in Recipes) + item.Current = item.ID == selected.ID; + CurrentRecipe = selected; + } + LoadRecipe(); + if (selected != null) + SendInfoDialog($"切换到配方:{selected.Name}"); + }); } + catch (Exception ex) + { + SendErrDialog($"加载配方失败:{ex.Message}"); + } + } + + private void LoadRecipe() + { // 重新加载画布配置和自定义控件 CurrentCanvasConfig = _DatasContext.CanvasConfigs.Where(c => c.RecipeID == CurrentRecipe.ID).FirstOrDefault(); diff --git a/PLCSharpWpf/Properties/AssemblyInfo.cs b/PLCSharpWpf/Properties/AssemblyInfo.cs index 547949d..5714990 100644 --- a/PLCSharpWpf/Properties/AssemblyInfo.cs +++ b/PLCSharpWpf/Properties/AssemblyInfo.cs @@ -12,4 +12,5 @@ // 如果此项目向 COM 公开,则下列 GUID 用于 typelib 的 ID。 -[assembly: Guid("4953e9f0-4cb5-486a-a3b2-637dcafd456c")] \ No newline at end of file +[assembly: Guid("4953e9f0-4cb5-486a-a3b2-637dcafd456c")] +[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("PLCSharp.Tests")] diff --git a/PLCSharpWpf/VVMs/Workflows/Workflow.cs b/PLCSharpWpf/VVMs/Workflows/Workflow.cs index 62b2e76..be8cd7f 100644 --- a/PLCSharpWpf/VVMs/Workflows/Workflow.cs +++ b/PLCSharpWpf/VVMs/Workflows/Workflow.cs @@ -3,7 +3,6 @@ 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; @@ -218,11 +217,11 @@ namespace PLCSharp.VVMs.Workflows private void ExecuteCompile() { - lock (this) + lock (_executionGate) { try { - if (IsRuning) + if (IsRuning || _activeRun != null) { DebugLog += "正在运行中,请先停止后再编译。\n"; return; @@ -298,92 +297,105 @@ namespace PLCSharp.VVMs.Workflows /// 全局模型 public void Run(GlobalModel globalModel) { - if (Assembly == null || !IsCompiled || Exception) + lock (_executionGate) { - IsRuning = false; - return; + if (_stopped || _activeRun != null || action == null || !IsCompiled || Exception) + return; + if (CompiledTime.AddSeconds(3) > DateTime.Now) return; + _activeRun = new(TaskCreationOptions.RunContinuationsAsynchronously); } - //刚编译完成的脚本,延迟3秒运行,避免编译后立即运行导致的异常 - if (CompiledTime.AddSeconds(3) > DateTime.Now) return; try { IsRuning = true; - action?.Invoke(globalModel, Flow); + action(globalModel, Flow); } catch (Exception ex) { Exception = true; - IsRuning = false; DebugLog += $"运行时异常: {ex}\n"; globalModel.SendErr($"运行时异常: {ex}\n"); } + finally + { + lock (_executionGate) + { + IsRuning = AutomaticExecution && !_stopped && !Exception; + _activeRun.TrySetResult(); + _activeRun = null; + } + } } - private BackgroundWorker _BackgroundWorker; + private readonly object _executionGate = new(); + private TaskCompletionSource _activeRun; + private CancellationTokenSource _scanCancellation; + private Task _scan = Task.CompletedTask; + private bool _stopped; - /// - /// 启动 - /// - /// 全局模型 public void Start(GlobalModel globalModel) { - GlobalModel = globalModel; - _BackgroundWorker = WorkerGuard.Watch(new BackgroundWorker { WorkerSupportsCancellation = true }, "工艺流程扫描"); - _BackgroundWorker.DoWork += BackgroundWork; - _BackgroundWorker.RunWorkerAsync(); - } - - /// - /// 停止 - /// - public void Stop() - { - - while (_BackgroundWorker != null && !_BackgroundWorker.CancellationPending) + lock (_executionGate) { - - _BackgroundWorker.CancelAsync(); - Thread.Sleep(0); + if (!_scan.IsCompleted || _activeRun != null) return; + _scanCancellation?.Dispose(); + _scanCancellation = new(); + _stopped = false; + var token = _scanCancellation.Token; + _scan = Task.Run(() => ScanAsync(globalModel, token)); } - - IsRuning = false; } - private void BackgroundWork(object sender, DoWorkEventArgs e) + // 保留脚本可调用的停止请求入口。替换配方或删除任务时必须等待 StopAsync。 + public void Stop() => _ = StopAsync(); + + public Task StopAsync() { - var worker = (BackgroundWorker)sender; - var sw = Stopwatch.StartNew(); - while (!worker.CancellationPending) + lock (_executionGate) { - sw.Restart(); - Thread.Sleep((int)(CycleDelayTime * 1000)); - if (AutomaticExecution) - { - Run(GlobalModel); - } - else + _stopped = true; + var canceled = _scanCancellation?.CancelAsync() ?? Task.CompletedTask; + if (_activeRun == null) { IsRuning = false; + return Task.WhenAll(_scan, canceled); } - sw.Stop(); - - if (!AutomaticExecution) - { - - Thread.Sleep(1000); - } - - CycleTime = sw.Elapsed.TotalSeconds; - if (Exception) - { - GlobalModel.ModeState.Sc.Stop = true; - } + return Task.WhenAll(_scan, canceled, _activeRun.Task); + } + } + + private async Task ScanAsync(GlobalModel globalModel, CancellationToken token) + { + var sw = new Stopwatch(); + try + { + while (!token.IsCancellationRequested) + { + sw.Restart(); + await Task.Delay((int)(CycleDelayTime * 1000), token).ConfigureAwait(false); + if (AutomaticExecution) + Run(globalModel); + else + { + lock (_executionGate) + { + if (_activeRun == null) IsRuning = false; + } + } + sw.Stop(); + if (!AutomaticExecution) + await Task.Delay(1000, token).ConfigureAwait(false); + CycleTime = sw.Elapsed.TotalSeconds; + if (Exception) + globalModel.ModeState.Sc.Stop = true; + } + } + catch (OperationCanceledException) when (token.IsCancellationRequested) { } + catch (Exception ex) + { + WorkerGuard.Report($"工艺流程扫描 异常停止:{ex}"); } - - } - private GlobalModel GlobalModel; private FlowModel _Flow = new(); /// diff --git a/PLCSharpWpf/VVMs/Workflows/WorkflowsModel.cs b/PLCSharpWpf/VVMs/Workflows/WorkflowsModel.cs index d5d2089..a9001f6 100644 --- a/PLCSharpWpf/VVMs/Workflows/WorkflowsModel.cs +++ b/PLCSharpWpf/VVMs/Workflows/WorkflowsModel.cs @@ -69,8 +69,26 @@ namespace PLCSharp.VVMs.Workflows public DelegateCommand Manage => _Manage ??= new DelegateCommand(ExecuteManage); + internal bool IsChangingRecipe { get; private set; } + + internal async Task ChangeRecipeAsync(Action loadRecipe) + { + if (IsChangingRecipe) return; + IsChangingRecipe = true; + try + { + await Task.WhenAll(Workflows.Select(flow => flow.StopAsync())); + loadRecipe(); + } + finally + { + IsChangingRecipe = false; + } + } + private void ExecuteManage(string cmd) { + if (IsChangingRecipe || _removingTask) return; switch (cmd) { case "New": @@ -120,17 +138,7 @@ public class Extension_" + newTask.ID.ToString().Replace("-", "") + { if (System.Windows.MessageBox.Show($"确认删除任务 [{SelectedTask.Name}]?", "确认删除", MessageBoxButton.YesNo, MessageBoxImage.Warning) != MessageBoxResult.Yes) break; - SelectedTask.Stop(); - var task = _DatasContext.Workflows.Where(c => c.ID == SelectedTask.ID).FirstOrDefault(); - if (task != null) - { - task.Stop(); - _DatasContext.Workflows.Remove(task); - _DatasContext.Save(); - } - var name = SelectedTask.Name; - Workflows.Remove(SelectedTask); - SendInfoDialog($"已删除:{name}"); + _ = RemoveTaskAsync(SelectedTask); } break; @@ -196,6 +204,32 @@ public class Extension_" + newTask.ID.ToString().Replace("-", "") + } } + private async Task RemoveTaskAsync(Workflow selected) + { + _removingTask = true; + try + { + await selected.StopAsync(); + var task = _DatasContext.Workflows.FirstOrDefault(c => c.ID == selected.ID); + if (task != null) + { + _DatasContext.Workflows.Remove(task); + _DatasContext.Save(); + } + Workflows.Remove(selected); + SendInfoDialog($"已删除:{selected.Name}"); + } + catch (Exception ex) + { + SendErrDialog($"删除任务失败:{ex.Message}"); + } + finally + { + _removingTask = false; + } + } + + private bool _removingTask; private bool editting; } } \ No newline at end of file diff --git a/Tests/PLCSharp.Tests/WorkflowRegressionTests.cs b/Tests/PLCSharp.Tests/WorkflowRegressionTests.cs new file mode 100644 index 0000000..5e8e201 --- /dev/null +++ b/Tests/PLCSharp.Tests/WorkflowRegressionTests.cs @@ -0,0 +1,93 @@ +using PLCSharp.Models; +using PLCSharp.VVMs.Workflows; +using Prism.Container.DryIoc; +using Prism.Ioc; +using System.IO; + +namespace PLCSharp.Tests; + +public class WorkflowRegressionTests +{ + private static readonly Lazy Compiler = new(() => + { + NatashaManagement.GetInitializer().WithMemoryUsing().WithMemoryReference() + .Preheating(); + return true; + }); + + private static Workflow Compile(string members) + { + _ = Compiler.Value; + var flow = new Workflow { CompiledTime = DateTime.MinValue }; + flow.Code = $"public class Extension_{flow.ID:N} {{ {members} }}"; + flow.Compile.Execute(); + return flow; + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task RecipeChangeWaitsForInFlightScriptAsync(bool automatic) + { + var path = Path.Combine(Path.GetTempPath(), $"{Guid.NewGuid():N}.db"); + try + { + using var db = new DatasContext(path); + IContainerExtension container = new DryIocContainerExtension(); + container.RegisterInstance(db); + var model = new WorkflowsModel(container, null!, null!); + var flow = Compile(""" + public static System.Threading.ManualResetEventSlim Release; + public void Run(PLCSharp.Models.GlobalModel model, PLCSharp.Core.Common.FlowModel flow) + { + flow.Step++; + Release.Wait(); + flow.Completed = true; + } + """); + Assert.True(flow.IsCompiled, flow.DebugLog); + using var release = new ManualResetEventSlim(); + flow.Assembly.GetTypes().Single(t => t.Name.StartsWith("Extension_")) + .GetField("Release")!.SetValue(null, release); + var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + flow.PropertyChanged += (_, e) => + { + if (e.PropertyName == nameof(flow.IsRuning) && flow.IsRuning) + entered.TrySetResult(); + }; + flow.AutomaticExecution = automatic; + model.Workflows.Add(flow); + flow.Start(null!); + var manual = automatic ? Task.CompletedTask : Task.Run(() => flow.Run(null!)); + try + { + await entered.Task.WaitAsync(TimeSpan.FromSeconds(10)); + bool loaded = false; + var change = model.ChangeRecipeAsync(() => + { + Assert.True(flow.Flow.Completed); + loaded = true; + }); + Assert.False(loaded); + Assert.False(change.IsCompleted); + await model.ChangeRecipeAsync(() => Assert.Fail("重复加载配方")); + release.Set(); + await change.WaitAsync(TimeSpan.FromSeconds(10)); + Assert.True(loaded); + flow.Run(null!); + Assert.Equal(1, flow.Flow.Step); + Assert.False(flow.IsRuning); + } + finally + { + release.Set(); + await Task.WhenAll(manual, flow.StopAsync()).WaitAsync(TimeSpan.FromSeconds(10)); + } + } + finally + { + Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools(); + File.Delete(path); + } + } +}