【发布时间】:2012-03-20 22:37:45
【问题描述】:
我在 C# 中异步读取一个进程的输出时遇到问题。 我在这个网站上发现了一些其他类似的问题,但它们并没有真正帮助我。 这是我的工作:
- 新建流程
- 设置启动信息 -FileName、参数、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();
}
【问题讨论】:
-
你有没有在appenline方法上下断点,看看它被命中了多少次?在控制台应用程序中,百分比是相互覆盖还是连续的?
-
百分比覆盖。我会放一个断点看看会发生什么...
-
它不是偶然称为 BeginOutputReadLine 的。该程序不输出任何行。除非程序显式调用flush(),否则在重定向输出时它通常不会输出任何内容。你无法解决这个问题。
标签: c# asynchronous process