0

The problem

I have a problem where an external process outputs text, but my C# application can't catch it. The external process keeps running forever and outputs text every now and then.

The following code works partially... The console opens but even thought the process is outputting data, nothing happens until I manually close the console window. At that point my Console window outputs what the external process had to say.

My Visual C# Form runs the following code:

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();

And

private void pOutputHandler( object sendingProcess, DataReceivedEventArgs outLine )
{
    Console.writeLine( outLine.data + Environment.NewLine;
}

What I have tried

  • When I set RedirectStandardInput, RedirectStandardOutput, RedirectStandardError and CreateNoWindow to true and uncomment the BeginOutputReadLine and BeginErrorReadLine lines, NOTHING AT ALL seems to be happening.
  • I modified the external process, making it output a string and close terminate. In that case my code (redirects and no comments) seemed to be working fine.

Assumption?

Could it be that my external process isn't really running, but stuck? Then why would it be stuck until I closed the Console window?

Additional information

While testing some more, I am beginning to think that this problem may come from the external process. I have written the following Process in C++:

int main()
{
    int x = 0;
    while( x < 100 )
    {
        Sleep( 100 );
        x = x + 1;
        cout << "Testing 123! " << x << "\r";
    }
    return 1;
}

While using this process as external process in my C# application, the output gets caught in my handler the moment the process is done and exited. How could it be that the asynchronous callback only catches output after the process exits? What can I do to prevent that from happening and catch the output "live"?

2

1 Answer 1

0

The solution

After looking into the documentation of C++, I came across the topic of "Flushing output buffers".

The only thing I had to do in the External process was adding the following line of code whenever I wanted the outputted text to be sent away immediately:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.