From 934bf1e729c12f316d1b80dde8ea88d939457426 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=E9=BE=99=E8=85=BE=E7=8C=AB=E8=B7=83?= <1043137532@qq.com>
Date: Mon, 15 Jun 2026 23:42:36 +0800
Subject: [PATCH] RunProgramAsync
---
Shared/MeloongCore.csproj | 14 ++++++-----
Shared/Utils/TaskUtils.cs | 50 ++++++++++++++++++++++++++++++++++++++
Wpf/MeloongCore.Wpf.csproj | 8 ++++++
3 files changed, 66 insertions(+), 6 deletions(-)
create mode 100644 Shared/Utils/TaskUtils.cs
diff --git a/Shared/MeloongCore.csproj b/Shared/MeloongCore.csproj
index 7756d01..ae55104 100644
--- a/Shared/MeloongCore.csproj
+++ b/Shared/MeloongCore.csproj
@@ -21,12 +21,6 @@
-
-
- ..\..\Plain Craft Launcher 2\Resources\Newtonsoft.Json.dll
-
-
-
@@ -35,9 +29,17 @@
+
+
+
+
+ ..\..\Plain Craft Launcher 2\Resources\Newtonsoft.Json.dll
+
+
+
$(DefineConstants);SNAPSHOT
diff --git a/Shared/Utils/TaskUtils.cs b/Shared/Utils/TaskUtils.cs
new file mode 100644
index 0000000..fc928ba
--- /dev/null
+++ b/Shared/Utils/TaskUtils.cs
@@ -0,0 +1,50 @@
+using System.Diagnostics;
+
+namespace MeloongCore;
+public static class TaskUtils {
+
+ public static void Run(this Task task) => task.GetAwaiter().GetResult();
+ public static T Run(this Task task) => task.GetAwaiter().GetResult();
+
+ ///
+ /// 静默运行程序并等待其结束,返回其输出和退出码。
+ /// 支持 notepad、git 等命令。
+ /// 超时或启动失败会抛出异常。
+ ///
+ public static async Task<(string Output, int ExitCode)> RunProgramAsync(string file, string arguments = "", int? timeoutMs = null, Encoding? encoding = null) {
+ Logger.Info($"运行程序,并返回其输出:{file} {arguments}");
+ var info = new ProcessStartInfo {
+ Arguments = arguments,
+ FileName = PathUtils.ToShortPath(file),
+ UseShellExecute = false,
+ CreateNoWindow = true,
+ RedirectStandardOutput = true, StandardOutputEncoding = encoding,
+ RedirectStandardError = true, StandardErrorEncoding = encoding
+ };
+ using var program = new Process { StartInfo = info, EnableRaisingEvents = true };
+ if (!program.Start()) throw new InvalidOperationException($"运行程序时出现意外错误:{file} {arguments}");
+
+ // 读取输出和错误流
+ var outputTask = program.StandardOutput.ReadToEndAsync();
+ var errorTask = program.StandardError.ReadToEndAsync();
+ var completionSource = new TaskCompletionSource