2017-09-28 36 views
0

在我的表單中,我通過運行一個可執行文件loader.exe(Visual Studio中的另一個項目)開始工作,該文件隨時間在控制檯上打印一些信息,直到它終止。我想要做的是: 我想在閱讀控制檯的同時繼續執行,並在我的表單應用程序的文本框textBoxConsole1中顯示最新輸出(帶有一些額外信息的百分比),以便用戶可以瞭解進度。讀取過程輸出[已更新]

編輯:目前,它有點複雜。它顯示一些輸出,然後顯示額外的輸出,然後顯示整個剩餘的輸出。與loader.exe不一樣。

在這個線程 C# Show output of Process in real time

Mr.Passant說:

「這是非常正常的,過程中會切換到時您重定向它的輸出緩衝輸出如果不吐一個。很多文字,那麼緩衝區不會填滿足夠導致它被刷新。如果你不能修復程序的代碼,你無能爲力。

那麼這個「足夠」到底有多少?我的代碼:

private void buttonConnect_Click(object sender, EventArgs e) 
    { 
     Thread findThread = new Thread(findProcedure); 
     findThread.Start(); 
    } 

    public void findProcedure() 
    { 
     Process process = new Process(); 
     process.StartInfo.FileName = PATH; 
     process.StartInfo.UseShellExecute = false; 
     process.StartInfo.RedirectStandardOutput = true; 
     process.StartInfo.RedirectStandardError = true; 
     process.StartInfo.RedirectStandardInput = true; 
     process.StartInfo.CreateNoWindow = true; 

     process.OutputDataReceived += new DataReceivedEventHandler((sender, e) => 
     { 
      if (!String.IsNullOrEmpty(e.Data)) 
      { 
       //textBoxConsole1.Text = e.Data; //Cross-thread validation exception 
       //use thread safe set method instead 
       setConsole1(e.Data); 
      } 
     }); 


     process.ErrorDataReceived += new DataReceivedEventHandler((sender, e) => 
     { 
      if (!String.IsNullOrEmpty(e.Data)) 
      { 
       setConsole3(e.Data); 
      } 
     }); 

     process.Start(); 
     process.BeginOutputReadLine(); 
     process.BeginErrorReadLine(); 

     process.WaitForExit(); 
    } 

而我的線程安全的設置方法:

public void setConsole1(string str) 
    { 
     if (this.textBoxConsole1.InvokeRequired) 
     { 
      SetTextCallback d = new SetTextCallback(setConsole1); 
      this.Invoke(d, new object[] { str }); 
     } 
     else 
     { 
      textBoxConsole1.AppendText(str); 
      textBoxConsole1.AppendText(Environment.NewLine); 
     } 
    } 

錯誤的數據處理方法setConsole3相同setConsole1,但套到另一個箱子。

+0

你好,歡迎來到SO,我們可以分享一些代碼,然後我們都可以看到它是如何工作的,哪些可能是錯誤的?你得到一個錯誤或什麼? 請參閱[如何提問](https://stackoverflow.com/help/how-to-ask)頁面以獲得澄清此問題的幫助。 – rmjoia

+0

看看:[https://stackoverflow.com/questions/285760/how-to-spawn-a-process-and-capture-its-stdout-in-net](https://stackoverflow.com/問題/ 285760 /怎樣生成一個進程並捕獲它的stdout-in-net) – corners

+0

@corners當生成它的進程終止但問題是我想捕獲它時該過程使用它,以便我可以看到我的表單上的進度 –

回答

0

您應該在StartInfo中將RedirectStandardOutput設置爲true。

Process process = new Process(); 
try 
{ 
    process.StartInfo.FileName = fileName // Loader.exe in this case; 
    ... 
    //other startInfo props 
    ... 
    process.StartInfo.RedirectStandardError = true; 
    process.StartInfo.RedirectStandardOutput = true; 
    process.OutputDataReceived += OutputReceivedHandler //OR (sender, e) => Console.WriteLine(e.Data); 
    process.ErrorDataReceived += ErrorReceivedHandler; 
    process.Start(); 
    process.BeginOutputReadline(); 
    process.BeginErrorReadLine(); 
    .... 
    //other thing such as wait for exit 
}