[英]Getting line by line output from a started process
我正在尝试检索由我启动的进程生成的输出行,这是代码
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
foreach (myData singleJob in e.Argument as List<myData>)
{
ProcessStartInfo psi = new ProcessStartInfo("myCommandLineProgram.exe");
psi.Arguments = "\"" + singleJob.row + "\"";
psi.CreateNoWindow = true;
psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
psi.RedirectStandardInput = true;
psi.RedirectStandardOutput = true;
psi.RedirectStandardError = true;
psi.UseShellExecute = false;
Process p = new Process();
p.StartInfo = psi;
p.Start();
StreamReader sr = p.StandardOutput ;
string line;
while ((line = sr.ReadLine()) != null )
{
this.Invoke((MethodInvoker)delegate
{
richTextBox1.AppendText(sr.ReadLine() + Environment.NewLine);
richTextBox1.ScrollToCaret();
});
}
//StreamReader streamOutput = p.StandardOutput;
//string content = streamOutput.ReadToEnd();
//this.Invoke((MethodInvoker)delegate
//{
// richTextBox1.AppendText(content + Environment.NewLine);
//});
p.WaitForExit();
}
}
尽管注释掉的代码始终有效(但是不能逐行解析),但是上面的代码还是有问题的,确实有些行无法显示在richtextbox中,而另一些则为空白。
谢谢
那不应该像
richTextBox1.AppendText(line + Environment.NewLine);
( line
而不是sr.ReadLine()
)?
两次调用readLine()
将每隔第二行丢弃一次。
另外,由于您在委托中调用ReadLine
,因此无法控制何时进行读取。 之间可能有多个ReadLines()
(来自while
行)。
请注意,您也不应使用line
变量:此变量在循环中始终引用同一行变量,在执行AppendText
时此变量可能包含新内容。 您应该在循环内引入一个新的局部变量,例如
while ((line = sr.ReadLine()) != null )
{
var theLine = line;
this.Invoke((MethodInvoker)delegate
{
richTextBox1.AppendText(theLine + Environment.NewLine);
richTextBox1.ScrollToCaret();
});
}
只是在这里更改而不是ReadLine()
,将line
放进去。 您已经在while循环中阅读了该行
string appendingLine = line;
this.Invoke((MethodInvoker)delegate
{
richTextBox1.AppendText(appendingLine + Environment.NewLine);
richTextBox1.ScrollToCaret();
});
编辑: MartinStettner给的答案是更好的选择。 可能存在在执行委托之前更改line
的情况,因此某些行可能会丢失,而其他行可能会重复。 因此,我将根据马丁的回答更改答案,我想指出的是,他应该是这一答案的功臣。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.