修复视觉步骤假超时:CTS 建了却从未传给 Task.Run,超时形同虚设
- 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 通过。
This commit is contained in:
parent
8c3a16bd03
commit
57c6dd9234
42
PLCSharpWpf/Core/Tools/TaskTool.cs
Normal file
42
PLCSharpWpf/Core/Tools/TaskTool.cs
Normal file
@ -0,0 +1,42 @@
|
||||
#nullable enable
|
||||
using System.Threading;
|
||||
|
||||
namespace PLCSharp.Core.Tools
|
||||
{
|
||||
/// <summary>
|
||||
/// 任务超时工具:给「不可取消的同步工作」套上真实的超时约束。
|
||||
/// </summary>
|
||||
public static class TaskTool
|
||||
{
|
||||
/// <summary>
|
||||
/// 在线程池上执行 <paramref name="work"/>,并最多等待 <paramref name="timeoutSeconds"/> 秒。
|
||||
/// <para>
|
||||
/// 超时抛 <see cref="TimeoutException"/>;调用方从此不再等待,流程状态机可以继续向下走或报错。
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// 注意:同步工作本身无法被强行中止——超时后该工作会被<b>放弃</b>(abandoned)并继续在自己的线程上跑完。
|
||||
/// 因此超时之后调用方必须认定这一步的结果不可信,并按失败处理(不能再使用它可能写坏的中间数据)。
|
||||
/// 放弃后的任务若再抛异常,不会落到当前调用方,而是由 <c>TaskScheduler.UnobservedTaskException</c> 记录。
|
||||
/// </para>
|
||||
/// </summary>
|
||||
/// <param name="work">要执行的工作(同步、不可取消)</param>
|
||||
/// <param name="timeoutSeconds">超时秒数;<= 0 表示不限时</param>
|
||||
/// <param name="cancellationToken">外部取消令牌(超时与取消共用一个等待过程)</param>
|
||||
/// <typeparam name="T">工作返回值类型</typeparam>
|
||||
/// <returns>工作的结果;超时抛 <see cref="TimeoutException"/>,取消抛 <see cref="OperationCanceledException"/></returns>
|
||||
public static Task<T> RunWithTimeoutAsync<T>(Func<T> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -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;
|
||||
}
|
||||
|
||||
76
Tests/PLCSharp.Tests/TaskToolTests.cs
Normal file
76
Tests/PLCSharp.Tests/TaskToolTests.cs
Normal file
@ -0,0 +1,76 @@
|
||||
#nullable enable
|
||||
using PLCSharp.Core.Tools;
|
||||
using System.Diagnostics;
|
||||
|
||||
namespace PLCSharp.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// TaskTool.RunWithTimeoutAsync 行为测试(回归:VisionFunction 曾经建了 CancellationTokenSource
|
||||
/// 却没把 Token 传给 Task.Run,导致「5 秒超时」完全不生效)。
|
||||
/// </summary>
|
||||
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<TimeoutException>(() =>
|
||||
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<OperationCanceledException>(() =>
|
||||
TaskTool.RunWithTimeoutAsync(() =>
|
||||
{
|
||||
Thread.Sleep(3000);
|
||||
return "never";
|
||||
}, 30, cts.Token));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RunWithTimeoutAsync_工作抛异常_应原样冒泡()
|
||||
{
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(() =>
|
||||
TaskTool.RunWithTimeoutAsync<string>(() => throw new InvalidOperationException("boom"), 5));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RunWithTimeoutAsync_work为null_应抛ArgumentNullException()
|
||||
{
|
||||
await Assert.ThrowsAsync<ArgumentNullException>(() =>
|
||||
TaskTool.RunWithTimeoutAsync<int>(null!, 5));
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user