我在 C# 中异步读取一个进程的输出时遇到问题。
我在这个网站上发现了一些其他类似的问题,但它们并没有真正帮助我。
这是我所做的:
- 制定新流程
- 设置启动信息
-文件名、参数、CreateNoWindow(true)、UseShellExecute(false)、RedirectStandardOutput(true)
- 将事件处理程序添加到 OutputDataReceived;
- 启动进程,BeginOutputReadLine,然后 WaitForExit()。
它工作正常,但所述过程的输出写入了一些百分比(%
)我想得到但我不能,因为我的代码逐行读取并且百分比不显示。
例子:
%0,%1...%100
Finished.
我的输出:
%0
Finished.
这是我的程序的当前代码:
StringBuilder sBuilder = new StringBuilder();
static void proc_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
sBuilder.AppendLine(e.Data);
}
static void CommandExecutor()
{
Process process = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = /*path of the program*/,
Arguments = /*arguments*/,
CreateNoWindow = true,
UseShellExecute = false,
WindowStyle = ProcessWindowStyle.Hidden,
RedirectStandardOutput = true
}
};
process.OutputDataReceived += new DataReceivedEventHandler(proc_OutputDataReceived);
process.Start();
process.BeginOutputReadLine();
process.WaitForExit();
}
Process.WaitForExit()
将等待直到异步输出/错误流读取完成。不幸的是,这不适用于Process.WaitForExit(timeout)
超载。这就是Process
类内部执行:
//...
finally
{
if (processWaitHandle != null)
{
processWaitHandle.Close();
}
if (this.output != null && milliseconds == -1)
{
this.output.WaitUtilEOF();
}
if (this.error != null && milliseconds == -1)
{
this.error.WaitUtilEOF();
}
this.ReleaseProcessHandle(safeProcessHandle);
}
...因此,只有在没有超时的情况下,它才会等待异步读取!
要修复它,只需调用parameterless WaitForExit()
after WaitForExit(timeout)
返回真:
// ...
if (process.WaitForExit( 10 * 1000 ) && process.WaitForExit() )
{
// Process'es OutputDataReceived / ErrorDataReceived callbacks will not be called again, EOF streams reached
}
else
{
throw new Exception("timeout");
}
详细信息请阅读此处的备注:http://msdn.microsoft.com/en-us/library/ty0d8k56%28v=vs.110%29 http://msdn.microsoft.com/en-us/library/ty0d8k56%28v=vs.110%29
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)