2009-12-10 30 views
2

我用C#勞克perl腳本的窗口形式的應用程序。C#程序給控制回父進程問題

一切工作,除了一個問題。當perl腳本運行時,它將作爲c#應用程序啓動的 進程運行。我在perl腳本 中有一些延遲等待來自套接字接口的消息。

由於這些延遲,當C#應用程序運行腳本,圖形用戶界面看起來像沒有響應狀態。我使用Process類來運行腳本。我的問題是,是 有辦法控制權給父進程,從Perl腳本 過程中的C#應用​​程序?我認爲在C#中的process.start()分叉新的進程,這應該不會影響GUI或C#應用程序本身 。

這裏是我的代碼開始perl腳本: 遍歷所有的Perl腳本... { 過程myProcess =新工藝(); MessageBox.Show((string)curScriptFileName);

  string ParentPath = findParentPath((string)curScriptFileName); 

      ProcessStartInfo myProcessStartInfo = new ProcessStartInfo("perl.exe"); 
      myProcessStartInfo.Arguments = (string)(curScriptFileName); 
      myProcessStartInfo.UseShellExecute = false; 
      myProcessStartInfo.RedirectStandardOutput = true; 
      myProcessStartInfo.WindowStyle = ProcessWindowStyle.Hidden; 
      myProcessStartInfo.CreateNoWindow = true; 
      myProcessStartInfo.WorkingDirectory = ParentPath; 
      myProcess.StartInfo = myProcessStartInfo; 
      myProcess.Start(); 

      // Read the standard output of the spawned process. 
      output = myProcess.StandardOutput.ReadToEnd(); 
      //MessageBox.Show(output); 
      //this.ScriptTestResultTextBox.AppendText(output); 
      //Console.WriteLine(output); 
      myProcess.WaitForExit(); 
     } 
     this.ScriptTestResultTextBox.AppendText(output); 

正如你所看到的,我習慣把文本框的附加碼內循環。我預計 ,我可以立即更新。但是現在,由於延遲,GUI沒有響應 我必須在進程退出後更新文本框。有沒有辦法解決這個問題?

感謝您的幫助。

+0

您可能對[此文章](http://www.codeducky.org/process-handling-net)感興趣,其中涵蓋了許多使用.NET過程的複雜問題,特別是在處理輸入和輸出。它推薦[MedallionShell](https://github.com/madelson/MedallionShell)庫,它簡化了io流的處理過程。 – ChaseMedallion 2014-08-29 01:41:33

回答

1

問題是,當您致電myProcess.StandardOutput.ReadToEnd()時,您正在導致C#應用程序阻止並等待產生的進程(Perl程序)完全結束並退出。因此,儘管Perl流程可以單獨運行並且不會影響父應用程序,但是您已經對父應用程序進行了編碼,以便它無法像您希望的那樣繼續運行。

解決這個問題的方法是使用一個單獨的線程或某種異步方法來收集輸出,讓你的主線程可以繼續運行和處理窗口消息。 @Rubens建議的BeginOutputReadLine方法是這樣做的一種方法,或者您可以通過QueueUserWorkItem使用線程池線程,甚至創建一個全新的線程。我的建議是從BeginOutputReadLine開始,只使用其他方法之一,如果不能滿足您的需求。