Windows 命名管道是進程間通訊(IPC)經典機制。傳統需呼叫 Win32 API(CreateNamedPipe、ConnectNamedPipe 等),C# 透過 System.Diagnostics.Process 導向標準輸出/輸入流,配合多執行緒非同步讀取,極大簡化管道實作。本文展示核心程式碼模式。
RedirectStandardOutput = true)StandardOutput 流AutoResetEvent 同步完成通知AppendText 避免閃爍Process proc = new Process();
proc.StartInfo.FileName = scriptPath; // 要執行的程式/腳本
proc.StartInfo.WorkingDirectory = workDir;
proc.StartInfo.CreateNoWindow = true; // 不建立視窗
proc.StartInfo.UseShellExecute = false; // 必須 false 才能導向
proc.StartInfo.RedirectStandardOutput = true; // 導向標準輸出
proc.Start();
AutoResetEvent outputEvent = new AutoResetEvent(false);
Thread outputThread = new Thread(DisplayOutput);
outputThread.Start();
WaitHandle.WaitAll(new WaitHandle[] { outputEvent }); // 等待讀取完成
private void DisplayOutput()
{
while (proc != null && !proc.HasExited)
{
string line;
while ((line = proc.StandardOutput.ReadLine()) != null)
{
// UI 更新必須在 UI 執行緒,這裡簡化示範
txtOutput.AppendText(line + "\r\n");
txtOutput.SelectionStart = txtOutput.Text.Length;
txtOutput.ScrollToCaret(); // 自動捲動到最新
}
Thread.Sleep(100); // 避免忙碌等待
}
outputEvent.Set(); // 通知完成
}
// 錯誤寫法:造成整個 TextBox 重繪閃爍
// txtOutput.Text += line + "\r\n";
// 正確寫法:僅追加,無閃爍
txtOutput.AppendText(line + "\r\n");
txtOutput.SelectionStart = txtOutput.Text.Length;
txtOutput.ScrollToCaret();
將整個「啟動進程 + 等待讀取完成」流程包裝在另一個背景執行緒中:
Thread worker = new Thread(() =>
{
Process proc = new Process();
// ... 設定 StartInfo ...
proc.Start();
AutoResetEvent evt = new AutoResetEvent(false);
Thread reader = new Thread(() =>
{
while (!proc.HasExited)
{
string line = proc.StandardOutput.ReadLine();
if (line != null)
{
// 跨執行緒 UI 更新需 Invoke
txtOutput.Invoke((MethodInvoker)delegate {
txtOutput.AppendText(line + "\r\n");
txtOutput.ScrollToCaret();
});
}
}
evt.Set();
});
reader.Start();
evt.WaitOne();
});
worker.Start();
若需雙向通訊,同樣設定 RedirectStandardInput = true,主進程透過 proc.StandardInput.WriteLine() 發送指令,子進程從 Console.ReadLine() 接收。
C# Process 類別封裝了複雜的管道建立與流導向細節,配合標準 .NET 串流與執行緒模型,讓開發者以極少程式碼實作健壯的進程間通訊。實務應用中建議加入逾時處理、編碼指定(StandardOutput.CurrentEncoding)、錯誤流(RedirectStandardError)導向等強化措施。