2008-10-02 110 views
8

我想從.NET程序中調用php-cgi.exe。我使用RedirectStandardOutput將輸出作爲流返回,但整個過程非常緩慢。在.NET中有效地重定向標準輸出

你有什麼想法讓我能更快地做出來嗎?任何其他技術?

Dim oCGI As ProcessStartInfo = New ProcessStartInfo() 
    oCGI.WorkingDirectory = "C:\Program Files\Application\php" 
    oCGI.FileName = "php-cgi.exe" 
    oCGI.RedirectStandardOutput = True 
    oCGI.RedirectStandardInput = True 
    oCGI.UseShellExecute = False 
    oCGI.CreateNoWindow = True 

    Dim oProcess As Process = New Process() 

    oProcess.StartInfo = oCGI 
    oProcess.Start() 

    oProcess.StandardOutput.ReadToEnd() 
+0

您可能會感興趣[此帖](http://www.codeducky.org/process-handling-net),它涵蓋了許多與.NET過程流工作的複雜性的。它推薦[MedallionShell](https://github.com/madelson/MedallionShell)庫,它極大地簡化了這類任務,並且可以使用異步來防止阻塞 – ChaseMedallion 2014-08-29 11:22:30

回答

7

您可以使用OutputDataReceived event接收數據,因爲它將數據泵送到StdOut。

+0

只是一個附註,我會將標準錯誤重定向到OutputDataReceived事件也是如此。然後您可以拋出一個新的異常或以另一種方式處理錯誤。 – 2008-10-03 00:34:17

+0

極好的一點! – 2008-10-03 03:05:13

15

我已經找到了最好的解決辦法是:

private void Redirect(StreamReader input, TextBox output) 
{ 
    new Thread(a => 
    { 
     var buffer = new char[1]; 
     while (input.Read(buffer, 0, 1) > 0) 
     { 
      output.Dispatcher.Invoke(new Action(delegate 
      { 
       output.Text += new string(buffer); 
      })); 
     }; 
    }).Start(); 
} 

private void Window_Loaded(object sender, RoutedEventArgs e) 
{ 
    process = new Process 
    { 
     StartInfo = new ProcessStartInfo 
     { 
      CreateNoWindow = true, 
      FileName = "php-cgi.exe", 
      RedirectStandardOutput = true, 
      UseShellExecute = false, 
      WorkingDirectory = @"C:\Program Files\Application\php", 
     } 
    }; 
    if (process.Start()) 
    { 
     Redirect(process.StandardOutput, textBox1); 
    } 
} 
2

這個問題是由於不良的php.ini配置。我遇到了同樣的問題,我從http://windows.php.net/download/下載了Windows安裝程序。

之後,並註釋掉不需要的擴展名,轉換過程是Speedy Gonzales,每秒轉換20 php。

您可以安全地使用「oProcess.StandardOutput.ReadToEnd()」。與使用線程解決方案相比,它的可讀性和易用性更高。要結合字符串使用線程解決方案,您需要引入事件或其他內容。

乾杯