
1. 項目概述從命令行到程序間通信在C#開發(fā)中尤其是開發(fā)桌面應用、工具軟件或者需要模塊化協(xié)作的系統(tǒng)時一個非常高頻且基礎(chǔ)的需求就是讓我的主程序去啟動另一個獨立的可執(zhí)行文件exe并且不是簡單地“打開它”而是要把一些關(guān)鍵信息“告訴”它。這個“告訴”的過程就是傳遞參數(shù)。聽起來簡單不就是把幾個字符串扔過去嗎但實際做起來從基礎(chǔ)的啟動到參數(shù)的正確格式化、特殊字符的轉(zhuǎn)義再到進程間的交互、錯誤處理每一步都可能藏著讓你調(diào)試半天的“坑”。我自己就經(jīng)歷過一個自動化測試工具需要調(diào)用外部的圖像處理exe并傳遞一個包含空格和中文路徑的文件名。直接在資源管理器里雙擊運行沒問題但用我的C#程序一調(diào)用那邊就報“文件未找到”。折騰了半天才發(fā)現(xiàn)是參數(shù)中的空格沒有被正確處理。這還只是冰山一角。隨著項目復雜度提升你可能還需要等待被調(diào)用程序執(zhí)行完畢、獲取它的輸出結(jié)果、甚至實時與其進行標準輸入輸出的交互。這些需求都遠遠超出了簡單的Process.Start(“notepad.exe”)。所以今天我們就來徹底拆解這個“C#程序啟動另一個exe并傳參”的課題。這不僅是語法問題更是一套關(guān)于進程間通信、資源管理和魯棒性設(shè)計的實踐。無論你是正在寫一個需要調(diào)用FFmpeg進行音視頻轉(zhuǎn)碼的工具還是開發(fā)一個集成多個第三方命令行工具的上位機或者是構(gòu)建一個模塊化的插件系統(tǒng)這篇文章里的內(nèi)容都能直接派上用場。我們會從最基礎(chǔ)的ProcessStartInfo和Arguments講起逐步深入到異步處理、輸出捕獲、錯誤流處理以及那些官方文檔里不會寫的實戰(zhàn)避坑指南。2. 核心原理與ProcessStartInfo深度解析為什么我們不能直接用Process.Start(“myapp.exe arg1 arg2”)這種看似直觀的方式呢在早期版本的 .NET 中確實有這種重載但它對復雜場景的控制力太弱。現(xiàn)代C#程序啟動外部進程核心是圍繞System.Diagnostics.Process類和它的搭檔ProcessStartInfo展開的。你可以把ProcessStartInfo看作一份詳細的“啟動任務說明書”而Process類是執(zhí)行這份說明書并管理后續(xù)進程生命的“管家”。2.1ProcessStartInfo關(guān)鍵屬性拆解創(chuàng)建一個ProcessStartInfo對象就相當于你在填寫這份說明書。下面這些屬性是你必須了解的FileName (string) 這是要啟動的exe的完整路徑。這是唯一一個必須設(shè)置的屬性。可以是絕對路徑如“C:\Tools\ffmpeg.exe”也可以是相對路徑或者如果該exe在系統(tǒng)環(huán)境變量PATH中可以直接寫文件名如“python”。注意 使用相對路徑時其基準目錄WorkingDirectory至關(guān)重要否則程序可能找不到依賴的DLL或配置文件。Arguments (string) 這就是我們要傳遞的參數(shù)列表。它是一個字符串而不是字符串數(shù)組。這意味著你需要把多個參數(shù)按照命令行規(guī)則拼接成一個字符串。這是所有問題的焦點我們會在下一章專門深入。UseShellExecute (bool) 這是一個極其重要的開關(guān)默認為true。它決定了啟動進程的方式。true 通過操作系統(tǒng)Shell如Windows的explorer.exe來啟動進程。這種方式可以打開文檔、URL如“http://...”或者關(guān)聯(lián)了默認程序的文件。但是在這種模式下你無法重定向進程的標準輸入、輸出和錯誤流StandardInput, Output, Error。false 直接創(chuàng)建新進程。這是我們需要與外部程序進行數(shù)據(jù)交互讀取其輸出、向其輸入命令時的必須設(shè)置。只有設(shè)置為false才能重定向流。RedirectStandardOutput / RedirectStandardError / RedirectStandardInput (bool) 當UseShellExecute false時這些屬性才有效。設(shè)置為true后你就可以通過Process.StandardOutput等流對象來讀取被調(diào)用程序的輸出或向其發(fā)送輸入。CreateNoWindow (bool) 當UseShellExecute false時有效。設(shè)置為true可以阻止被調(diào)用程序創(chuàng)建控制臺窗口。這對于后臺靜默運行命令行工具非常有用。WorkingDirectory (string) 設(shè)置新進程的初始工作目錄。很多程序會基于當前目錄尋找配置文件或處理相對路徑的文件。如果不設(shè)置默認繼承當前調(diào)用程序的目錄。WindowStyle (ProcessWindowStyle) 控制啟動后窗口的狀態(tài)如Normal,Hidden,Minimized,Maximized。注意如果CreateNoWindow true這個設(shè)置可能不生效。2.2 基礎(chǔ)啟動流程與代碼骨架理解了核心屬性一個最基礎(chǔ)的、帶有參數(shù)傳遞的啟動流程代碼如下所示。這是你后續(xù)所有復雜操作的起點。using System.Diagnostics; public void StartExeWithArgs() { // 1. 創(chuàng)建并配置“啟動任務說明書” ProcessStartInfo startInfo new ProcessStartInfo(); startInfo.FileName C:\MyTools\Converter.exe; // 目標exe路徑 startInfo.Arguments -input D:\test file.txt -output D:\result.txt -overwrite; // 參數(shù)字符串 startInfo.UseShellExecute false; // 如需交互必須設(shè)為false startInfo.CreateNoWindow true; // 不顯示黑框窗口 startInfo.WorkingDirectory C:\MyTools\; // 設(shè)置工作目錄 // 2. 創(chuàng)建“進程管家”并關(guān)聯(lián)說明書 Process process new Process(); process.StartInfo startInfo; try { // 3. 啟動進程 bool started process.Start(); if (started) { Console.WriteLine($進程已啟動ID: {process.Id}); // 此處可以添加等待結(jié)束、讀取輸出等操作見后續(xù)章節(jié) process.WaitForExit(); // 等待進程結(jié)束 int exitCode process.ExitCode; Console.WriteLine($進程結(jié)束退出代碼: {exitCode}); } } catch (Exception ex) { // 4. 異常處理例如文件不存在、權(quán)限不足 Console.WriteLine($啟動進程失敗: {ex.Message}); } finally { // 5. 釋放資源 process?.Dispose(); } }這個骨架涵蓋了從配置、啟動到基礎(chǔ)資源管理的完整鏈條。接下來我們要攻克其中最易出錯的部分Arguments字符串的構(gòu)建。3. 參數(shù)字符串構(gòu)建的藝術(shù)與陷阱Arguments屬性是一個字符串但命令行解析有其古老而復雜的規(guī)則。構(gòu)建不當輕則參數(shù)傳遞錯誤重則引發(fā)安全漏洞如命令注入。我們的目標是讓我們的C#程序構(gòu)建出的參數(shù)字符串與用戶在CMD中手動輸入的效果完全一致。3.1 基礎(chǔ)規(guī)則與拼接假設(shè)我們要調(diào)用一個假想的工具Processor.exe它接受兩個參數(shù)一個輸入文件和一個輸出目錄。在CMD中我們這樣寫Processor.exe C:\My Documents\input.dat D:\Output Folder在C#中Arguments就應該設(shè)置為startInfo.Arguments C:\My Documents\input.dat D:\Output Folder;注意路徑兩邊的雙引號是參數(shù)字符串的一部分用來告訴命令行解析器“這是一個整體參數(shù)即使內(nèi)部有空格”。在C#字符串中雙引號需要用另一個雙引號進行轉(zhuǎn)義所以看起來是...。對于簡單的、不含空格的參數(shù)直接拼接即可string mode encode; int quality 90; startInfo.Arguments $-mode {mode} -quality {quality}; // 生成-mode encode -quality 903.2 處理特殊字符與安全轉(zhuǎn)義當參數(shù)值來自用戶輸入或變量時直接拼接是危險的。例如string userInput “filename.txt”; // 用戶輸入了 startInfo.Arguments $-input {userInput}; // 生成-input filename.txt在Windows命令提示符中是命令分隔符這會導致name.txt被當作一個新命令解析可能引發(fā)意外執(zhí)行。解決方案是使用系統(tǒng)提供的轉(zhuǎn)義方法System.Security.SecurityElement.Escape雖然常用于XML但對于簡單的轉(zhuǎn)義并非最佳。更通用的做法是對于可能包含空格、引號、、|、、 等特殊字符的參數(shù)始終為其加上雙引號。但更穩(wěn)健的方式是使用 .NET 提供的專用類。從 .NET Core 3.0 / .NET 5 開始強烈推薦使用System.CommandLine命名空間外的CommandLineBuilder或更底層的System.Diagnostics.Process相關(guān)的輔助方法實際上.NET Framework 和 .NET Core 早期版本沒有內(nèi)置完美的解決方案。一個廣泛接受的實踐是模仿System.CommandLine的內(nèi)部邏輯或使用社區(qū)庫但對于大多數(shù)場景遵循以下規(guī)則手動處理是可行的參數(shù)值本身不含雙引號用雙引號包裹整個值。value-value。參數(shù)值本身包含雙引號這是最復雜的情況。Windows命令行解析器使用反斜杠\來轉(zhuǎn)義雙引號。規(guī)則是用雙引號包裹整個值并將值內(nèi)部的所有雙引號替換為\。例如要傳遞參數(shù)He said, Hello World.正確的Arguments字符串應為He said, \Hello World\.在C#代碼中startInfo.Arguments He said, \Hello World\.;(看起來復雜但遵循規(guī)則即可)。為了簡化我們可以編寫一個輔助方法public static string EscapeCommandLineArgument(string argument) { // 空參數(shù)直接返回空字符串 if (string.IsNullOrEmpty(argument)) return string.Empty; // 如果參數(shù)不含空格、制表符、雙引號可以直接返回可選優(yōu)化但為了安全統(tǒng)一加引號更簡單 // 這里采用更安全的策略總是用雙引號包裹并轉(zhuǎn)義內(nèi)部的雙引號 StringBuilder sb new StringBuilder(); sb.Append(); foreach (char c in argument) { if (c ) { sb.Append(\\); // 在雙引號前添加反斜杠 sb.Append(); } else if (c \\) { // 處理反斜杠在參數(shù)末尾的連續(xù)反斜杠需要特殊處理這里簡化處理 sb.Append(\\); } else { sb.Append(c); } } sb.Append(); return sb.ToString(); } // 使用 string arg1 EscapeCommandLineArgument(C:\My Files\data.txt); string arg2 EscapeCommandLineArgument(Text with \quotes\ inside.); startInfo.Arguments ${arg1} {arg2};3.3 使用System.CommandLine進行現(xiàn)代化構(gòu)建.NET 5如果你的項目基于較新的.NET版本.NET 5, 6, 7, 8等處理命令行參數(shù)有一個更現(xiàn)代、更強大的官方方案System.CommandLine。雖然它主要用于構(gòu)建你自己的命令行應用程序但其底層用于轉(zhuǎn)義和拼接參數(shù)的邏輯是可靠且經(jīng)過充分測試的。我們可以“借用”它的CommandLineBuilder來安全地構(gòu)建參數(shù)字符串。首先通過NuGet安裝System.CommandLine包。using System.CommandLine; public static string BuildCommandLineArguments(params string[] args) { var commandLineBuilder new CommandLineBuilder(); foreach (var arg in args) { commandLineBuilder.AddArgument(arg); } // CommandLineBuilder 內(nèi)部會正確處理轉(zhuǎn)義 return commandLineBuilder.Build().Arguments; } // 使用示例 string safeArguments BuildCommandLineArguments( -input, C:\My Files\input.txt, -message, He said, Hello World. ); // safeArguments 將是: -input C:\\My Files\\input.txt -message He said, \Hello World\. startInfo.Arguments safeArguments;這種方法將轉(zhuǎn)義的復雜性交給了成熟可靠的庫極大地減少了出錯的可能尤其是在處理用戶提供的、不可預知的輸入時。4. 高級交互捕獲輸出、輸入與異步控制僅僅啟動進程并傳遞參數(shù)往往不夠。我們通常需要獲取外部程序執(zhí)行后的結(jié)果控制臺輸出。在外部程序運行時向其發(fā)送指令標準輸入。不阻塞主線程地等待進程結(jié)束異步操作。處理標準錯誤流以區(qū)分正常日志和錯誤信息。這些功能都要求將ProcessStartInfo.UseShellExecute設(shè)置為false。4.1 同步讀取輸出與錯誤這是最常見的場景啟動一個命令行工具等它跑完然后讀取它打印的所有內(nèi)容。public (string output, string error, int exitCode) RunCommandSync(string fileName, string arguments) { var outputBuilder new StringBuilder(); var errorBuilder new StringBuilder(); var startInfo new ProcessStartInfo { FileName fileName, Arguments arguments, UseShellExecute false, RedirectStandardOutput true, RedirectStandardError true, CreateNoWindow true, StandardOutputEncoding Encoding.UTF8, // 重要指定輸出編碼避免中文亂碼 StandardErrorEncoding Encoding.UTF8 }; using (var process new Process { StartInfo startInfo }) { // 設(shè)置輸出/錯誤數(shù)據(jù)接收事件 process.OutputDataReceived (sender, e) { if (!string.IsNullOrEmpty(e.Data)) outputBuilder.AppendLine(e.Data); }; process.ErrorDataReceived (sender, e) { if (!string.IsNullOrEmpty(e.Data)) errorBuilder.AppendLine(e.Data); }; process.Start(); // 開始異步讀取輸出和錯誤流 process.BeginOutputReadLine(); process.BeginErrorReadLine(); // 等待進程退出 process.WaitForExit(); // 確保所有異步讀取完成 process.WaitForExit(); // 第二次調(diào)用WaitForExit以確保所有數(shù)據(jù)被接收某些場景下需要 // 或者使用 process.CancelOutputRead(); process.CancelErrorRead(); 來結(jié)束讀取 return (outputBuilder.ToString(), errorBuilder.ToString(), process.ExitCode); } }關(guān)鍵點RedirectStandardOutput和RedirectStandardError必須設(shè)為true。通過事件OutputDataReceived和ErrorDataReceived來異步接收數(shù)據(jù)。如果使用process.StandardOutput.ReadToEnd()同步讀取在輸出量很大時可能導致死鎖如果子進程同時向錯誤流填充大量數(shù)據(jù)而父進程未讀取。指定編碼 (StandardOutputEncoding)至關(guān)重要特別是被調(diào)用程序輸出中文等非ASCII字符時。默認編碼可能是系統(tǒng)活動代碼頁導致亂碼。通常設(shè)為Encoding.UTF8是安全的選擇前提是外部程序也使用UTF8輸出。WaitForExit()必須在BeginOutputReadLine()之后調(diào)用以確保進程結(jié)束后事件仍能處理完緩沖區(qū)中的數(shù)據(jù)。4.2 實現(xiàn)異步等待與實時交互對于執(zhí)行時間較長或需要實時查看進度、進行交互的程序同步等待會阻塞UI線程導致程序“卡死”。我們需要異步操作。public async Task(string output, string error, int exitCode) RunCommandAsync(string fileName, string arguments, CancellationToken cancellationToken default) { var outputBuilder new StringBuilder(); var errorBuilder new StringBuilder(); var startInfo new ProcessStartInfo { FileName fileName, Arguments arguments, UseShellExecute false, RedirectStandardOutput true, RedirectStandardError true, CreateNoWindow true, StandardOutputEncoding Encoding.UTF8, StandardErrorEncoding Encoding.UTF8 }; using (var process new Process { StartInfo startInfo }) { var tcs new TaskCompletionSourceint(); process.Exited (sender, args) { tcs.TrySetResult(process.ExitCode); }; process.EnableRaisingEvents true; // 必須設(shè)置為true才能觸發(fā)Exited事件 process.OutputDataReceived (sender, e) { if (!string.IsNullOrEmpty(e.Data)) { outputBuilder.AppendLine(e.Data); // 可以在這里實時處理每一行輸出例如更新UI進度條 OnOutputDataReceived?.Invoke(this, e.Data); } }; process.ErrorDataReceived (sender, e) { if (!string.IsNullOrEmpty(e.Data)) errorBuilder.AppendLine(e.Data); }; process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); // 使用Task.WhenAny來同時等待進程結(jié)束和取消令牌 var exitTask tcs.Task; var completedTask await Task.WhenAny(exitTask, Task.Delay(Timeout.Infinite, cancellationToken)); if (completedTask exitTask) { // 進程正常結(jié)束 await exitTask; // 確保獲取ExitCode return (outputBuilder.ToString(), errorBuilder.ToString(), process.ExitCode); } else { // 被取消 try { process.Kill(); } catch { /* 忽略殺死進程時的異常 */ } cancellationToken.ThrowIfCancellationRequested(); return (outputBuilder.ToString(), errorBuilder.ToString(), -1); // 或用特定代碼表示取消 } } } // 定義事件用于實時回調(diào)輸出 public event EventHandlerstring OnOutputDataReceived;關(guān)鍵點使用process.EnableRaisingEvents true和process.Exited事件來感知進程結(jié)束而不是阻塞的WaitForExit()。將進程結(jié)束封裝為一個Task便于使用async/await進行異步等待。整合了CancellationToken允許用戶取消長時間運行的任務并優(yōu)雅地終止外部進程。通過事件OnOutputDataReceived實現(xiàn)了輸出數(shù)據(jù)的實時回調(diào)這對于需要顯示實時日志的GUI應用非常有用。4.3 向進程發(fā)送輸入標準輸入有些交互式命令行工具如mysql客戶端、某些配置腳本需要從標準輸入讀取命令。我們可以通過RedirectStandardInput并向process.StandardInput流寫入數(shù)據(jù)來實現(xiàn)。public void SendInputToProcess() { var startInfo new ProcessStartInfo { FileName python, Arguments -i, // 以交互模式啟動Python UseShellExecute false, RedirectStandardInput true, RedirectStandardOutput true, RedirectStandardError true, CreateNoWindow false, // 這里可以顯示窗口觀察 StandardOutputEncoding Encoding.UTF8 }; using (var process Process.Start(startInfo)) using (var writer process.StandardInput) using (var reader process.StandardOutput) { if (writer.BaseStream.CanWrite) { // 向Python交互環(huán)境發(fā)送命令 writer.WriteLine(print(Hello from C#)); writer.WriteLine(x 5 3); writer.WriteLine(print(fx {x})); writer.WriteLine(exit()); // 發(fā)送退出命令 writer.Flush(); } // 讀取Python的輸出 string output reader.ReadToEnd(); Console.WriteLine(Python輸出:); Console.WriteLine(output); process.WaitForExit(); } }重要警告 向標準輸入寫入后必須關(guān)閉輸入流writer.Close()或process.StandardInput.Close()以告知子進程輸入已結(jié)束。否則子進程可能會一直等待更多輸入導致ReadToEnd()掛起。5. 實戰(zhàn)避坑指南與高級技巧掌握了基本方法和高級交互后我們來看看那些只有踩過坑才知道的細節(jié)和優(yōu)化技巧。5.1 路徑、環(huán)境變量與工作目錄的坑相對路徑的陷阱 當FileName是相對路徑如“tool.exe”時系統(tǒng)會在PATH環(huán)境變量中查找但也會受到WorkingDirectory的影響。最穩(wěn)妥的方式是如果可能始終使用可執(zhí)行文件的絕對路徑。如果必須用相對路徑明確設(shè)置startInfo.WorkingDirectory到該exe所在的目錄或其預期的上下文目錄。使用Path.Combine(AppDomain.CurrentDomain.BaseDirectory, “tools”, “myapp.exe”)來構(gòu)建基于你應用程序啟動目錄的絕對路徑。環(huán)境變量繼承 默認情況下子進程會繼承父進程的所有環(huán)境變量。你可以通過startInfo.EnvironmentVariables字典來添加、修改或刪除特定的環(huán)境變量。startInfo.EnvironmentVariables[MY_CUSTOM_VAR] SomeValue; // 如果需要也可以清除繼承的變量 // startInfo.EnvironmentVariables.Clear();中文路徑與編碼 除了之前提到的輸出流編碼參數(shù)字符串本身也可能包含中文。確保你的C#源文件保存的編碼通常是UTF-8 with BOM與系統(tǒng)控制臺代碼頁匹配不是必須的因為參數(shù)是通過進程創(chuàng)建API傳遞的不是通過控制臺字符串。但為了最大兼容性在構(gòu)建參數(shù)字符串時使用正常的C#字符串即可.NET會處理Unicode到ANSI如果需要的轉(zhuǎn)換。更復雜的情況涉及被調(diào)用程序是原生Win32程序且期望ANSI字符串這時可能需要使用Encoding.Default進行轉(zhuǎn)換但現(xiàn)代程序大多能處理Unicode路徑。5.2 進程生命周期管理與資源釋放using語句是必須的Process類實現(xiàn)了IDisposable。務必將其包裹在using語句中或在finally塊中調(diào)用Dispose()。否則即使進程退出一些系統(tǒng)句柄可能仍被占用導致資源泄漏。等待超時與強制終止process.WaitForExit(int milliseconds)可以指定超時時間。如果超時你可能需要決定是否強制終止進程 (process.Kill())。Kill()是強制性的可能阻止子進程進行清理工作。更好的做法是先嘗試友好地關(guān)閉例如向標準輸入發(fā)送退出命令或發(fā)送關(guān)閉消息給GUI程序僅在超時后使用Kill。if (!process.WaitForExit(30000)) // 等待30秒 { Console.WriteLine(進程未在指定時間內(nèi)結(jié)束嘗試強制終止。); process.Kill(); // 注意Kill之后可能需要再WaitForExit一下確保進程完全退出 process.WaitForExit(); }處理子進程的子進程process.Kill()通常只殺死直接啟動的進程。如果這個進程又創(chuàng)建了子進程例如你的C#程序啟動了cmd.execmd.exe又啟動了ping.exeKill可能不會殺死孫子進程。在Windows上你可以使用作業(yè)對象 (Job Object) 來管理進程樹但這涉及更復雜的P/Invoke編程。5.3 性能與穩(wěn)定性考量避免頻繁啟動進程 啟動進程是相對昂貴的操作。如果需要在循環(huán)中多次調(diào)用同一個輕量級工具考慮是否可以將該工具的功能集成到主程序中或者使用進程池、保持一個進程實例并通過標準輸入進行多次交互如果工具支持。輸出緩沖區(qū)死鎖 這是經(jīng)典陷阱。如果一個子進程向標準輸出寫入大量數(shù)據(jù)同時向標準錯誤流也寫入大量數(shù)據(jù)而父進程只讀取其中一個流例如只用StandardOutput.ReadToEnd()緩沖區(qū)可能會被填滿導致子進程阻塞等待父進程讀取而父進程又在等待子進程退出形成死鎖。解決方案就是始終使用異步讀取 (BeginOutputReadLine) 或同時異步讀取兩個流如前文示例所示。提升權(quán)限以管理員身份運行 如果你的程序需要啟動一個需要管理員權(quán)限的exe而你的主程序本身不是以管理員運行的直接啟動會失敗。你可以設(shè)置startInfo.Verb “runas”;。當UseShellExecute true時這會觸發(fā)UAC提權(quán)對話框。startInfo.FileName net.exe; startInfo.Arguments start someservice; startInfo.Verb runas; // 請求提升權(quán)限 startInfo.UseShellExecute true; // Verb需要UseShellExecute為true Process.Start(startInfo);注意設(shè)置Verb “runas”后你將無法重定向輸入輸出流因為UseShellExecute必須為true。6. 綜合案例封裝一個健壯的外部進程調(diào)用器結(jié)合以上所有知識點我們可以設(shè)計一個相對健壯、易用的輔助類用于處理大多數(shù)外部進程調(diào)用場景。using System; using System.Diagnostics; using System.Text; using System.Threading; using System.Threading.Tasks; public class ExternalProcessRunner { public class ExecutionResult { public int ExitCode { get; set; } public string StandardOutput { get; set; } string.Empty; public string StandardError { get; set; } string.Empty; public bool TimedOut { get; set; } public TimeSpan ExecutionTime { get; set; } } public static async TaskExecutionResult RunAsync( string fileName, string arguments, string workingDirectory null, int timeoutMilliseconds Timeout.Infinite, CancellationToken cancellationToken default, Actionstring onOutputReceived null, Actionstring onErrorReceived null) { var result new ExecutionResult(); var stopwatch Stopwatch.StartNew(); var outputBuilder new StringBuilder(); var errorBuilder new StringBuilder(); var startInfo new ProcessStartInfo { FileName fileName, Arguments arguments, UseShellExecute false, RedirectStandardOutput true, RedirectStandardError true, CreateNoWindow true, StandardOutputEncoding Encoding.UTF8, StandardErrorEncoding Encoding.UTF8, }; if (!string.IsNullOrEmpty(workingDirectory)) startInfo.WorkingDirectory workingDirectory; using (var process new Process { StartInfo startInfo }) using (var cts CancellationTokenSource.CreateLinkedTokenSource(cancellationToken)) { if (timeoutMilliseconds ! Timeout.Infinite) { cts.CancelAfter(timeoutMilliseconds); } var tcs new TaskCompletionSourcebool(); process.Exited (sender, args) tcs.TrySetResult(true); process.EnableRaisingEvents true; process.OutputDataReceived (sender, e) { if (e.Data ! null) { outputBuilder.AppendLine(e.Data); onOutputReceived?.Invoke(e.Data); } }; process.ErrorDataReceived (sender, e) { if (e.Data ! null) { errorBuilder.AppendLine(e.Data); onErrorReceived?.Invoke(e.Data); } }; try { process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); // 等待進程退出或取消/超時 await Task.WhenAny(tcs.Task, Task.Delay(Timeout.Infinite, cts.Token)); if (cts.Token.IsCancellationRequested) { result.TimedOut (timeoutMilliseconds ! Timeout.Infinite); // 嘗試友好終止然后強制終止 if (!process.HasExited) { process.CloseMainWindow(); // 對GUI程序可能有效 await Task.Delay(500); if (!process.HasExited) process.Kill(); } // 等待進程實際退出 await Task.Run(() process.WaitForExit(5000)); if (cancellationToken.IsCancellationRequested) cancellationToken.ThrowIfCancellationRequested(); else throw new TimeoutException($進程執(zhí)行超時 ({timeoutMilliseconds}ms)。); } else { // 進程正常退出確保拿到最終退出碼 await tcs.Task; } // 再給一點時間讓異步讀取事件處理完最后的數(shù)據(jù) await Task.Delay(100); } finally { stopwatch.Stop(); result.ExecutionTime stopwatch.Elapsed; if (process.HasExited) { result.ExitCode process.ExitCode; } result.StandardOutput outputBuilder.ToString().TrimEnd(); result.StandardError errorBuilder.ToString().TrimEnd(); } } return result; } // 同步版本簡化適用于簡單場景 public static ExecutionResult Run( string fileName, string arguments, string workingDirectory null, int timeoutMilliseconds Timeout.Infinite) { // 注意同步版本無法很好地處理實時輸出回調(diào) var task RunAsync(fileName, arguments, workingDirectory, timeoutMilliseconds); task.Wait(); // 在UI線程上調(diào)用此方法會導致死鎖謹慎使用 return task.Result; } } // 使用示例 public async Task UseRunnerAsync() { var result await ExternalProcessRunner.RunAsync( fileName: ffmpeg.exe, arguments: $-i \{inputVideo}\ -c:v libx264 -crf 23 \{outputVideo}\, workingDirectory: C:\FFmpeg\bin, timeoutMilliseconds: 300000, // 5分鐘超時 onOutputReceived: (line) Console.WriteLine($[FFmpeg] {line}), onErrorReceived: (line) Console.Error.WriteLine($[FFmpeg Error] {line}) ); if (result.ExitCode 0) { Console.WriteLine($轉(zhuǎn)換成功耗時{result.ExecutionTime.TotalSeconds:F2}秒); } else { Console.WriteLine($轉(zhuǎn)換失敗退出碼{result.ExitCode}); Console.WriteLine($錯誤輸出{result.StandardError}); } }這個ExternalProcessRunner類封裝了超時控制、取消支持、實時輸出回調(diào)、完整的輸出/錯誤捕獲以及基本的資源管理。它為你處理了大部分繁瑣和易錯的細節(jié)讓你可以更專注于業(yè)務邏輯。在實際項目中你可能還需要根據(jù)具體需求對其進行擴展比如添加環(huán)境變量配置、更精細的進程樹管理、或者更復雜的錯誤重試邏輯。