plcsharp/PLCSharpWpf/Core/Tools/TaskTool.cs
tfarcraw 24325d2535 补齐文件编码:把编辑过程中被丢掉的 UTF-8 BOM 和 LF 行尾归一回仓库约定
本仓库的 .cs 都是 UTF-8 with BOM + CRLF。前面几个提交里,编辑工具把 App.xaml.cs、LoginModel.cs、VisionFunction.cs 首行的 BOM 掉了(表现为每个提交都多出一行无关的 -using/+using diff);新建的 TaskTool.cs、WorkerGuard.cs 及三个测试文件则是无 BOM 的 LF。

这里统一补回 BOM、行尾归一为 CRLF。改动只是编码,逐文件 diff 都只有首行一处,无代码变化。
2026-11-17 23:30:49 +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);
}
}
}