【发布时间】:2013-05-01 14:43:02
【问题描述】:
问题
我有一个问题,外部进程输出文本,但我的 C# 应用程序无法捕获它。 外部进程一直运行,不时输出文本。
以下代码部分工作...控制台打开但即使进程正在输出数据,在我手动关闭控制台窗口之前什么都没有发生。那时我的控制台窗口会输出外部进程必须说的内容。
我的 Visual C# 窗体运行以下代码:
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.FileName = "MyFile.exe";
p.StartInfo.Arguments = "arguments";
p.StartInfo.RedirectStandardInput = false;
p.StartInfo.RedirectStandardOutput = false;
p.StartInfo.RedirectStandardError = false;
p.StartInfo.CreateNoWindow = false;
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
p.OutputDataReceived += new DataReceivedEventHandler( pOutputHandler );
p.ErrorDataReceived += new DataReceivedEventHandler( pOutputHandler );
started = p.Start();
//p.BeginOutputReadLine();
//p.BeginErrorReadLine();
和
private void pOutputHandler( object sendingProcess, DataReceivedEventArgs outLine )
{
Console.writeLine( outLine.data + Environment.NewLine;
}
我尝试过的
- 当我将
RedirectStandardInput、RedirectStandardOutput、RedirectStandardError和CreateNoWindow设置为 true 并取消注释BeginOutputReadLine和BeginErrorReadLine行时,似乎什么都没有发生。 - 我修改了外部进程,使其输出字符串并关闭终止。在那种情况下,我的代码(重定向且没有 cmets)似乎运行良好。
假设?
会不会是我的外部进程并没有真正运行,而是卡住了?那为什么在我关闭控制台窗口之前它会卡住呢?
其他信息
在进行更多测试时,我开始认为这个问题可能来自外部进程。我用 C++ 编写了以下流程:
int main()
{
int x = 0;
while( x < 100 )
{
Sleep( 100 );
x = x + 1;
cout << "Testing 123! " << x << "\r";
}
return 1;
}
在我的 C# 应用程序中将此进程用作外部进程时,当进程完成并退出时,输出会在我的处理程序中被捕获。异步回调怎么可能只在进程退出后才捕获输出?我能做些什么来防止这种情况发生并“实时”捕获输出?
【问题讨论】:
-
您是否尝试过使用后台工作程序? msdn.microsoft.com/en-us/library/cc221403(v=vs.95).aspx 我建议您也看看这篇文章,因为它更具体地针对您正在尝试做的事情(运行外部可执行文件)stackoverflow.com/questions/13150171/…
-
既然
OutputDataReceived和ErrorDataReceived是异步运行的,我不明白为什么应该这样做?
标签: c# process console-application