我試圖執行一個命令行程序,並打印其輸出到實時文本框:文本框沒有得到來自不同的線程更新,除非顯示的MessageBox
private void btnExecute_Click(object sender, EventArgs e)
{
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.CreateNoWindow = true;
startInfo.FileName = Application.StartupPath + "\\Deps\\ats.exe";
startInfo.UseShellExecute = false;
startInfo.RedirectStandardOutput = true;
using (Process exeProcess = Process.Start(startInfo))
{
exeProcess.OutputDataReceived += exeProcess_OutputDataReceived;
exeProcess.BeginOutputReadLine();
//MessageBox.Show("Hello"); //Notice this message box before calling WaitForExit
exeProcess.WaitForExit(45000);
}
private void exeProcess_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
if (txtOutput.InvokeRequired)
{
txtOutput.Invoke(new MethodInvoker(delegate { txtOutput.Text += Environment.NewLine + e.Data; }));
}
}
}
的代碼運行沒有錯誤,但不打印任何東西到txtOutput 然而,如果我取消註釋消息框,消息框顯示和txtOutput實時更新 現在如果我點擊'確定'關閉消息框,txtOutput停止更新再次!
這裏究竟發生了什麼?爲什麼只有當我顯示MessageBox時才更新textBox?
我懷疑你是不是真正從控制檯應用程序的方式,你得到的輸出認爲你是(我的控制檯重定向有點生疏)。在代理中放置一些調試代碼,將'e.Data'輸出到調試窗口,以驗證你實際上是否獲得了一些輸出。 – CodingGorilla
@CodingGorilla,我知道我從控制檯應用程序的輸出,因爲只要MessageBox顯示文本框顯示輸出,但只要我關閉消息框輸出停止更新 – user3006467