From 57c6dd9234f276b24b822221e705f90c9a2a427d Mon Sep 17 00:00:00 2001 From: tfarcraw <123211521@163.com> Date: Tue, 17 Nov 2026 23:14:32 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E8=A7=86=E8=A7=89=E6=AD=A5?= =?UTF-8?q?=E9=AA=A4=E5=81=87=E8=B6=85=E6=97=B6=EF=BC=9ACTS=20=E5=BB=BA?= =?UTF-8?q?=E4=BA=86=E5=8D=B4=E4=BB=8E=E6=9C=AA=E4=BC=A0=E7=BB=99=20Task.R?= =?UTF-8?q?un=EF=BC=8C=E8=B6=85=E6=97=B6=E5=BD=A2=E5=90=8C=E8=99=9A?= =?UTF-8?q?=E8=AE=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - VisionFunction.RunAllAsync case 3:原来新建 CancellationTokenSource(5s) 但 await Task.Run(...) 没有传 token, 于是 catch (OperationCanceledException) when (cts.IsCancellationRequested) 永远不命中;相机掉线或算法卡死时 RunAllAsync 永不返回,且硬编码 5 秒与文案里读的 Flow.TimeoutSeconds 不一致(该配置项此前完全无效)。 - 新增 Core/Tools/TaskTool.RunWithTimeoutAsync:Task.Run + Task.WaitAsync 真实限时, <=0 作为显式关闭超时的逃生门;超时后明确按「步骤被放弃、结果不可信」处理。 - 超时改用 FlowModel.TimeoutSeconds(单步超时现在是可配置的)。 - 新增 6 个 TaskTool 回归测试(含「等待必须停在超时点」的时间断言)。构建 0 error,测试 49/49 通过。 --- PLCSharpWpf/Core/Tools/TaskTool.cs | 42 +++++++++++++ PLCSharpWpf/VVMs/Vision/VisionFunction.cs | 14 ++--- Tests/PLCSharp.Tests/TaskToolTests.cs | 76 +++++++++++++++++++++++ 3 files changed, 125 insertions(+), 7 deletions(-) create mode 100644 PLCSharpWpf/Core/Tools/TaskTool.cs create mode 100644 Tests/PLCSharp.Tests/TaskToolTests.cs diff --git a/PLCSharpWpf/Core/Tools/TaskTool.cs b/PLCSharpWpf/Core/Tools/TaskTool.cs new file mode 100644 index 0000000..25b769c --- /dev/null +++ b/PLCSharpWpf/Core/Tools/TaskTool.cs @@ -0,0 +1,42 @@ +#nullable enable +using System.Threading; + +namespace PLCSharp.Core.Tools +{ + /// + /// 任务超时工具:给「不可取消的同步工作」套上真实的超时约束。 + /// + public static class TaskTool + { + /// + /// 在线程池上执行 ,并最多等待 秒。 + /// + /// 超时抛 ;调用方从此不再等待,流程状态机可以继续向下走或报错。 + /// + /// + /// 注意:同步工作本身无法被强行中止——超时后该工作会被放弃(abandoned)并继续在自己的线程上跑完。 + /// 因此超时之后调用方必须认定这一步的结果不可信,并按失败处理(不能再使用它可能写坏的中间数据)。 + /// 放弃后的任务若再抛异常,不会落到当前调用方,而是由 TaskScheduler.UnobservedTaskException 记录。 + /// + /// + /// 要执行的工作(同步、不可取消) + /// 超时秒数;<= 0 表示不限时 + /// 外部取消令牌(超时与取消共用一个等待过程) + /// 工作返回值类型 + /// 工作的结果;超时抛 ,取消抛 + public static Task RunWithTimeoutAsync(Func work, double timeoutSeconds, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(work); + + var task = Task.Run(work, cancellationToken); + + // timeoutSeconds <= 0 作为「显式关闭超时」的逃生门,保持老行为可被选择 + if (timeoutSeconds <= 0 || double.IsNaN(timeoutSeconds) || double.IsInfinity(timeoutSeconds)) + { + return task; + } + + return task.WaitAsync(TimeSpan.FromSeconds(timeoutSeconds), cancellationToken); + } + } +} diff --git a/PLCSharpWpf/VVMs/Vision/VisionFunction.cs b/PLCSharpWpf/VVMs/Vision/VisionFunction.cs index dd5e1b7..71616a3 100644 --- a/PLCSharpWpf/VVMs/Vision/VisionFunction.cs +++ b/PLCSharpWpf/VVMs/Vision/VisionFunction.cs @@ -1,4 +1,4 @@ -using OpenCvSharp; +using OpenCvSharp; using PLCSharp.Core.Common; using PLCSharp.Core.Prism; using PLCSharp.Core.Tools; @@ -315,14 +315,13 @@ namespace PLCSharp.VVMs.Vision case 3: { - // 设置 5 秒超时 - using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); + // 单步超时:取 FlowModel.TimeoutSeconds(<=0 表示不限时) var item = VisionFlows[index]; + var timeoutSeconds = Flow.TimeoutSeconds; try { - item.Flow.StepTime = DateTime.Now; - var result = await Task.Run(() => RunItem(item)); + var result = await TaskTool.RunWithTimeoutAsync(() => RunItem(item), timeoutSeconds); item.CT = Math.Round(Sw.ElapsedMilliseconds / 1000.0, 3); // 转换为秒 Sw.Stop(); if (result) @@ -337,11 +336,12 @@ namespace PLCSharp.VVMs.Vision Flow.Completed = true; } } - catch (OperationCanceledException) when (cts.IsCancellationRequested) + catch (TimeoutException) { + // 超时后该步骤被放弃:它可能仍在自己的线程上跑完,其结果一律视为不可信 Sw.Stop(); item.CT = Math.Round(Sw.ElapsedMilliseconds / 1000.0, 3); // 转换为秒 - item.Flow.FailMessage = $"执行超时(>{Flow.TimeoutSeconds:F0}秒)"; + item.Flow.FailMessage = $"执行超时(>{timeoutSeconds:F0}秒),该步骤已被放弃"; Flow.Success = false; Flow.Completed = true; } diff --git a/Tests/PLCSharp.Tests/TaskToolTests.cs b/Tests/PLCSharp.Tests/TaskToolTests.cs new file mode 100644 index 0000000..7c031b9 --- /dev/null +++ b/Tests/PLCSharp.Tests/TaskToolTests.cs @@ -0,0 +1,76 @@ +#nullable enable +using PLCSharp.Core.Tools; +using System.Diagnostics; + +namespace PLCSharp.Tests; + +/// +/// TaskTool.RunWithTimeoutAsync 行为测试(回归:VisionFunction 曾经建了 CancellationTokenSource +/// 却没把 Token 传给 Task.Run,导致「5 秒超时」完全不生效)。 +/// +public class TaskToolTests +{ + [Fact] + public async Task RunWithTimeoutAsync_正常返回_应回传结果() + { + var result = await TaskTool.RunWithTimeoutAsync(() => 42, 5); + + Assert.Equal(42, result); + } + + [Fact] + public async Task RunWithTimeoutAsync_工作超时_应抛TimeoutException() + { + var sw = Stopwatch.StartNew(); + + await Assert.ThrowsAsync(() => + TaskTool.RunWithTimeoutAsync(() => + { + Thread.Sleep(2000); + return "never"; + }, 0.2)); + + sw.Stop(); + // 关键断言:等待真的在超时点结束,而不是等工作跑完(2 秒) + Assert.True(sw.Elapsed.TotalSeconds < 1.5, $"实际等待 {sw.Elapsed.TotalSeconds:F2} 秒,超时未生效"); + } + + [Fact] + public async Task RunWithTimeoutAsync_超时秒数为0_应表示不限时() + { + var result = await TaskTool.RunWithTimeoutAsync(() => + { + Thread.Sleep(50); + return "ok"; + }, 0); + + Assert.Equal("ok", result); + } + + [Fact] + public async Task RunWithTimeoutAsync_外部取消_应抛OperationCanceledException() + { + using var cts = new CancellationTokenSource(100); + + await Assert.ThrowsAnyAsync(() => + TaskTool.RunWithTimeoutAsync(() => + { + Thread.Sleep(3000); + return "never"; + }, 30, cts.Token)); + } + + [Fact] + public async Task RunWithTimeoutAsync_工作抛异常_应原样冒泡() + { + await Assert.ThrowsAsync(() => + TaskTool.RunWithTimeoutAsync(() => throw new InvalidOperationException("boom"), 5)); + } + + [Fact] + public async Task RunWithTimeoutAsync_work为null_应抛ArgumentNullException() + { + await Assert.ThrowsAsync(() => + TaskTool.RunWithTimeoutAsync(null!, 5)); + } +}