切换配方前等待旧工作流退出

This commit is contained in:
wanglei 2026-12-05 20:01:10 +08:00
parent 3ebbd31103
commit 5c022bfd26
5 changed files with 243 additions and 106 deletions

View File

@ -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<MessageEvent>().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();

View File

@ -12,4 +12,5 @@
// 如果此项目向 COM 公开,则下列 GUID 用于 typelib 的 ID。
[assembly: Guid("4953e9f0-4cb5-486a-a3b2-637dcafd456c")]
[assembly: Guid("4953e9f0-4cb5-486a-a3b2-637dcafd456c")]
[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("PLCSharp.Tests")]

View File

@ -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
/// <param name="globalModel">全局模型</param>
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;
/// <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)
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();
/// <summary>

View File

@ -69,8 +69,26 @@ namespace PLCSharp.VVMs.Workflows
public DelegateCommand<string> Manage =>
_Manage ??= new DelegateCommand<string>(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;
}
}

View File

@ -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<bool> Compiler = new(() =>
{
NatashaManagement.GetInitializer().WithMemoryUsing().WithMemoryReference()
.Preheating<NatashaDomainCreator>();
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);
}
}
}