【发布时间】:2014-06-26 23:42:05
【问题描述】:
我正在尝试执行命令行程序并将其实时打印输出到文本框:
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 打印任何内容 但是,如果我取消注释消息框,则会显示 MessageBox 并实时更新 txtOutput 现在,如果我单击“确定”关闭 MessageBox,txtOutput 将再次停止更新!
这里到底发生了什么?为什么只有在显示 MessageBox 时才会更新 textBox?
【问题讨论】:
-
我怀疑您实际上并没有像您想象的那样从控制台应用程序获取输出(我的控制台重定向有点生疏)。将一些调试代码放入您的委托中,以将
e.Data输出到调试窗口,以验证您实际上得到了一些输出。 -
@CodingGorilla,我知道我正在从控制台应用程序获取输出,因为只要显示 MessageBox,文本框就会显示输出,但只要我关闭消息框,输出就会停止更新跨度>
标签: c# multithreading user-interface