plcsharp/PLCSharpWpf/Core/Tools/TaskTool.cs
tfarcraw 57c6dd9234 修复视觉步骤假超时: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 通过。
2026-11-17 23:14:32 +08:00

43 lines
2.2 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#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">超时秒数;&lt;= 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);
}
}
}