【问题标题】:C# Catching live output from process returns nothing while prosess is runningC# 从进程捕获实时输出在进程运行时不返回任何内容
【发布时间】: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# 应用程序中将此进程用作外部进程时,当进程完成并退出时,输出会在我的处理程序中被捕获。异步回调怎么可能只在进程退出后才捕获输出?我能做些什么来防止这种情况发生并“实时”捕获输出?

【问题讨论】:

标签: c# process console-application


【解决方案1】:

解决方案

在查看了 C++ 的文档后,我遇到了“刷新输出缓冲区”的主题。

我在外部进程中唯一需要做的就是在我希望立即发送输出文本时添加以下代码行:

cout << "Some string" << someVar;
cout << flush;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-27
    • 1970-01-01
    相关资源
    最近更新 更多