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)); + } +}