RunProgramAsync 支持取消、TaskUtils.ForEachAsync

This commit is contained in:
龙腾猫跃 committed 2026-06-23 00:40:27 +08:00
1 parent b6873fd850
commit 907021bdb2
2 files changed
+37 -11

No files matched your search

+1 -3
View File
@@ -104,12 +104,12 @@ public static class ConfigUtils {
public class ConfigEntry<T>(string key, T? defaultValue, IConfigProvider? defaultProvider = null, bool encrypted = false) { public class ConfigEntry<T>(string key, T? defaultValue, IConfigProvider? defaultProvider = null, bool encrypted = false) {
public IConfigProvider DefaultProvider => defaultProvider ?? ConfigUtils.AppData;
/// <summary> /// <summary>
/// 当设置项的值实际被改变时触发,参数为新值。 /// 当设置项的值实际被改变时触发,参数为新值。
/// </summary> /// </summary>
public event Action<T?, IConfigProvider>? Changed; public event Action<T?, IConfigProvider>? Changed;
public IConfigProvider DefaultProvider => defaultProvider ?? ConfigUtils.AppData;
public void Edit(Func<T?, T?> editFunc, IConfigProvider? providerOverride = null) { public void Edit(Func<T?, T?> editFunc, IConfigProvider? providerOverride = null) {
var provider = providerOverride ?? DefaultProvider; var provider = providerOverride ?? DefaultProvider;
Set(editFunc(Get(provider)), provider); Set(editFunc(Get(provider)), provider);
@@ -139,7 +139,5 @@ public class ConfigEntry<T>(string key, T? defaultValue, IConfigProvider? defaul
=> (providerOverride ?? DefaultProvider).Read(key, defaultValue, encrypted); => (providerOverride ?? DefaultProvider).Read(key, defaultValue, encrypted);
public bool HasValue(IConfigProvider? providerOverride = null) public bool HasValue(IConfigProvider? providerOverride = null)
=> (providerOverride ?? DefaultProvider).HasValue(key); => (providerOverride ?? DefaultProvider).HasValue(key);
public void Save(IConfigProvider? providerOverride = null)
=> (providerOverride ?? DefaultProvider).Save();
public static implicit operator T?(ConfigEntry<T> entry) => entry.Get(); public static implicit operator T?(ConfigEntry<T> entry) => entry.Get();
} }
+36 -8
View File
@@ -11,7 +11,8 @@ public static class TaskUtils {
/// 支持 notepad、git 等命令。 /// 支持 notepad、git 等命令。
/// 超时或启动失败会抛出异常。 /// 超时或启动失败会抛出异常。
/// </summary> /// </summary>
public static async Task<(string Output, int ExitCode)> RunProgramAsync(string file, string arguments = "", int? timeoutMs = null, Encoding? encoding = null) { public static async Task<(string Output, int ExitCode)> RunProgramAsync(string file, string arguments = "", int? timeoutMs = null, Encoding? encoding = null, CancellationToken cancellationToken = default) {
cancellationToken.ThrowIfCancellationRequested();
var info = new ProcessStartInfo { var info = new ProcessStartInfo {
Arguments = arguments, Arguments = arguments,
FileName = PathUtils.ToShortPath(file), FileName = PathUtils.ToShortPath(file),
@@ -25,27 +26,54 @@ public static class TaskUtils {
bool hasTimeout = timeoutMs.HasValue && timeoutMs > 0; bool hasTimeout = timeoutMs.HasValue && timeoutMs > 0;
Logger.Info($"运行程序,并返回其输出:{file} {arguments}{(hasTimeout ? $",最长可等待 {timeoutMs}ms" : "")}"); Logger.Info($"运行程序,并返回其输出:{file} {arguments}{(hasTimeout ? $",最长可等待 {timeoutMs}ms" : "")}");
// 读取输出和错误流 // 输出和错误流
var outputTask = program.StandardOutput.ReadToEndAsync(); var outputTask = program.StandardOutput.ReadToEndAsync();
var errorTask = program.StandardError.ReadToEndAsync(); var errorTask = program.StandardError.ReadToEndAsync();
var completionSource = new TaskCompletionSource<object?>(TaskCreationOptions.RunContinuationsAsynchronously); var completionSource = new TaskCompletionSource<object?>(TaskCreationOptions.RunContinuationsAsynchronously);
program.Exited += (_, _) => completionSource.TrySetResult(null); program.Exited += (_, _) => completionSource.TrySetResult(null);
if (program.HasExited) completionSource.TrySetResult(null); if (program.HasExited) completionSource.TrySetResult(null);
var task = completionSource.Task; var task = completionSource.Task;
var timeoutTask = Task.Delay(hasTimeout ? timeoutMs!.Value : Timeout.Infinite);
// 等待超时 var cancelTask = Task.Delay(Timeout.Infinite, cancellationToken);
if (hasTimeout) {
Logger.Trace($"等待程序 {program.Id} 完成"); Logger.Trace($"等待程序 {program.Id} 完成");
if (await Task.WhenAny(task, Task.Delay(timeoutMs!.Value)) != task) { var completedTask = await Task.WhenAny(task, timeoutTask, cancelTask);
if (completedTask != task) {
try { try {
if (!program.HasExited) program.Kill(); if (!program.HasExited) program.Kill();
} catch (InvalidOperationException) { // 进程已退出,无需处理 } catch (InvalidOperationException) { // 进程已退出,无需处理
} }
if (completedTask == cancelTask) throw new OperationCanceledException(cancellationToken);
throw new TimeoutException($"运行程序超时:{file} {arguments}"); throw new TimeoutException($"运行程序超时:{file} {arguments}");
} }
}
await task;
return (await outputTask + await errorTask, program.ExitCode); return (await outputTask + await errorTask, program.ExitCode);
} }
public static async Task ForEachAsync<T>(IEnumerable<T> source, int maxDegreeOfParallelism, Func<T, CancellationToken, Task> body, CancellationToken cancellationToken = default) {
using var linkedCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
var token = linkedCancellationTokenSource.Token;
var enumeratorLock = new object();
using var enumerator = source.GetEnumerator();
async Task WorkerAsync() {
try {
while (true) {
T item;
lock (enumeratorLock) {
token.ThrowIfCancellationRequested();
if (!enumerator.MoveNext()) return;
item = enumerator.Current;
}
await body(item, token).ConfigureAwait(false);
}
} catch {
try {
linkedCancellationTokenSource.Cancel(); // 让尚未开始的 worker 尽快停止
} catch {
}
throw;
}
}
await Task.WhenAll([.. Enumerable.Range(0, maxDegreeOfParallelism).Select(_ => Task.Run(WorkerAsync))]).ConfigureAwait(false);
}
} }