[英]C# Reading a console application in a loop
我需要循环执行许多文件的控制台应用程序并更新GUI。 当我第一次执行我的应用程序时,一切正常,GUI更新是实时完成的。 但是,每次迭代,控制台输出的读取都会有更长的延迟。 在3-4个文件之后,我只有很少的更新,或者根本没有更新。 更新GUI并不是问题,我的dataraceivedevent不会启动。
我不明白为什么,因为在每次迭代之后,我都会关闭并处理我的过程。
这是我在for循环中执行的方法。
public void execute(string arguments, string path)
{
Process myProcess = new Process();
myProcess.StartInfo.CreateNoWindow = true;
myProcess.StartInfo.FileName = path;
myProcess.StartInfo.UseShellExecute = false;
myProcess.StartInfo.RedirectStandardOutput = true;
myProcess.StartInfo.Arguments = arguments;
myProcess.Start();
myProcess.BeginOutputReadLine();
myProcess.OutputDataReceived += new DataReceivedEventHandler(this.updateProgress);
myProcess.WaitForExit();
myProcess.CancelOutputRead();
myProcess.OutputDataReceived -= updateProgress;
myProcess.Close();
myProcess.Dispose();
if (progressBar1.InvokeRequired)
{
progressBar1.BeginInvoke(new Action(() =>
{
progressBar1.PerformStep();
}));
}
else
{
progressBar1.PerformStep();
}
if (progressBar2.InvokeRequired)
{
progressBar2.BeginInvoke(new Action(() =>
{
progressBar2.Value = 100;
progressBar2.Refresh();
}));
}
else
{
progressBar2.Value = 100;
progressBar2.Refresh();
}
if (this.InvokeRequired)
{
this.BeginInvoke(new Action(() =>
{
this.Text = " ";
}));
}
else
{
this.Text = " ";
}
Thread.Sleep(500);
}
请致电.BeginOutputReadLine();
.OutputDataReceived += new DataReceivedEventHandler(...);
之后的方法.OutputDataReceived += new DataReceivedEventHandler(...);
在开始阅读之前(附加事件之前),可能发生了OutputDataReceived
事件。
http://msdn.microsoft.com/zh-CN/library/system.diagnostics.process.beginoutputreadline.aspx
喜欢:
myProcess.OutputDataReceived += new DataReceivedEventHandler(this.updateProgress);
myProcess.BeginOutputReadLine();
执行10万次后,我遇到了同样的问题,最后一次是myProcess.WaitForExit();
花了很多时间。 相反,您可以使用另一个重载,该重载取一个整数,该整数指示进程有时间退出多少毫秒。 myProcess.WaitForExit(1000);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.