首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 實現 Windows 管道技術:Process 標準輸出重導向與非同步讀取執行緒

     編輯:關於C語言

核心思路

利用 Process 類別啟動子進程,將 StandardOutput 重導向,另開執行緒持續讀取並即時顯示於 TextBox,不阻塞主 UI 執行緒。

1. 啟動進程並重導向輸出

Process proc = new Process();
proc.StartInfo.FileName = strScript;        // 腳本/可執行檔路徑
proc.StartInfo.WorkingDirectory = strDirectory;
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.UseShellExecute = false;     // 必須 false 才能重導向
proc.StartInfo.RedirectStandardOutput = true;
proc.Start();

2. 背景執行緒讀取輸出

AutoResetEvent eventOutput = new AutoResetEvent(false);
Thread threadOutput = new Thread(DisplayOutput) { IsBackground = true };
threadOutput.Start();
WaitHandle.WaitAll(new[] { eventOutput }); // 等待讀取結束 (可選)

3. 讀取執行緒邏輯

private void DisplayOutput()
{
    while (proc != null && !proc.HasExited)
    {
        string line;
        while ((line = proc.StandardOutput.ReadLine()) != null)
        {
            txtOutput.AppendText(line + "\r\n");
            txtOutput.SelectionStart = txtOutput.Text.Length;
            txtOutput.ScrollToCaret(); // 自動捲動到最新
        }
        Thread.Sleep(100); // 降低 CPU 佔用
    }
    eventOutput.Set(); // 通知完成
}

關鍵細節

  • AppendText + SelectionStart/ScrollToCaret 避免 += 導致整個 TextBox 重繪閃爍。
  • UseShellExecute=false 是重導向前提。
  • 整個流程放入背景執行緒,主 UI 保持響應。

此模式適用於呼叫命令列工具、編譯器、腳本並即時捕獲輸出的場景。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved