这是什么问题,为什么richtextbox无法获取Process输出流? richtextbox中没有文本显示。
private void button1_Click(object sender, EventArgs e)
{
Process sortProcess;
sortProcess = new Process();
sortProcess.StartInfo.FileName = "sort.exe";
sortProcess.StartInfo.Arguments = this.comboBox1.SelectedItem.ToString();
// Set UseShellExecute to false for redirection.
sortProcess.StartInfo.CreateNoWindow = true;
sortProcess.StartInfo.UseShellExecute = false;
// Redirect the standard output of the sort command.
// This stream is read asynchronously using an event handler.
sortProcess.StartInfo.RedirectStandardOutput = true;
sortOutput = new StringBuilder("");
// Set our event handler to asynchronously read the sort output.
sortProcess.OutputDataReceived += new DataReceivedEventHandler(SortOutputHandler);
// Redirect standard input as well. This stream
// is used synchronously.
sortProcess.StartInfo.RedirectStandardInput = true;
// Start the process.
sortProcess.Start();
// Start the asynchronous read of the sort output stream.
sortProcess.BeginOutputReadLine();
sortProcess.WaitForExit();
richTextBox1.AppendText(sortOutput.ToString());
}
private static void SortOutputHandler(object sendingProcess,
DataReceivedEventArgs outLine)
{
sortOutput.Append(Environment.NewLine +
"[" + numOutputLines.ToString() + "] - " + outLine.Data);
}
}
因此,当sort.exe启动时,它会显示文本,我希望所有这些文本也实时显示在richtextbox中(我不想等待进程退出,然后读取所有输出)
我该怎么做?我的代码有任何错误的部分吗?谢谢
更新@botz
我在我的代码中添加了这个
private void SortOutputHandler(object sendingProcess,
DataReceivedEventArgs outLine)
{
sortOutput.Append(Environment.NewLine +
"[" + numOutputLines.ToString() + "] - " + outLine.Data);
richTextBox1.AppendText(sortOutput.ToString());
}
但是它抛出了这个异常
Cross-thread operation not valid: Control 'richTextBox1' accessed from a thread other than the thread it was created on.
最佳答案
WaitForExit()会阻止您的UI线程,因此您看不到新的输出。
在单独的线程中等待该过程,或者将WaitForExit()
替换为以下内容:
while (!sortProcess.HasExited) {
Application.DoEvents(); // This keeps your form responsive by processing events
}
现在,在
SortOutputHandler
中,您可以直接将输出追加到文本框。但是您应该记住检查是否需要在UI线程上调用它。您可以在处理程序中以这种方式检查它是否在UI线程上:
if (richTextBox1.InvokeRequired) { richTextBox1.BeginInvoke(new DataReceivedEventHandler(SortOutputHandler), new[] { sendingProcess, outLine }); }
else {
sortOutput.Append(Environment.NewLine + "[" + numOutputLines.ToString() + "] - " + outLine.Data);
richTextBox1.AppendText(sortOutput.ToString());
}
关于c# - 如何将流程输出(控制台)重定向到richtextbox?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6521475/