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

C# 實作 Windows 管道技術:進程間通訊輕鬆上手

     編輯:關於C#

Windows 命名管道是進程間通訊(IPC)經典機制。傳統需呼叫 Win32 API(CreateNamedPipe、ConnectNamedPipe 等),C# 透過 System.Diagnostics.Process 導向標準輸出/輸入流,配合多執行緒非同步讀取,極大簡化管道實作。本文展示核心程式碼模式。

核心架構

  1. 啟動子進程,導向標準輸出(RedirectStandardOutput = true)
  2. 主執行緒建立工作執行緒持續讀取 StandardOutput 流
  3. 使用 AutoResetEvent 同步完成通知
  4. UI 介面以 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(); // 通知完成
}

關鍵 UI 更新技巧

// 錯誤寫法:造成整個 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)導向等強化措施。

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