Running Process from another Process

  • Thread starter Thread starter Gidi
  • Start date Start date
G

Gidi

Hi,

I'm trying to run a process and catch it's output and display it in a
richTextBox.
the process I'm running, runs some other processes, I'm using Thread to run
this process, my problem is, that in the stage that the new process starts,
there is no output, and the thread "thinks" the process is over and finishes.
if i'm not using theards, it's works fine, but then i can't write the output
to my RichTextBox.

can some one help me?

here is some of my code:

private void ReadStdOutputThreadProc()
{
while (!c_Process.HasExited)
{
try
{
string str = c_StreamOutput.ReadLine();
while (!c_StreamOutput.EndOfStream)
{
c_StreamOutput.BaseStream.Flush();
Thread.Sleep(100);
if (str != null && str != String.Empty)
{
richTextBox1.Invoke((MethodInvoker)delegate {
richTextBox1.Text += Environment.NewLine + str; });
}

str = c_StreamOutput.ReadLine();
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
}
 
Hi,

Thanks for your help.

Peter Duniho said:
It's difficult from your code sample to understand exactly what you're
trying to do or why it's not working for you. I didn't see anything in
your code that would cause the basic loop to exit before the process has..
However, there are some obvious problems with the code, so we can start
there. :)

First: don't poll Process.HasExited. In your case, reaching the end of
the output stream is sufficient. For code that's not reading from the
output stream, it's better to subscribe to the Process.Exited event and
use that for notification.

Second: there's no need to check for StreamReader.EndOfStream.
StreamReader.ReadLine() will return null when it reaches the end of the
stream.

Third: don't call Stream.Flush() on the output stream you're reading.
This is pointless. You're not writing to the stream, so there's no way
that there could be any buffered data you've sent to the stream that needs
to be flushed.

Finally: don't call Thread.Sleep(). There's really no point in doing
that, as your thread will yield anyway any time there's no output to read,
as well as when Invoke() is called. This is not a thread that's going to
be hogging the CPU, nor is it a thread that you really want to slow down..

IMHO, your method body would look something more like this:

string str;

while ((str = c_StreamOutput.ReadLine()) != null)
{
richTextBox1.Invoke((MethodInvoker)delegate
{ richTextBox1.Text += Environment.NewLine + str; } );
}

You can optionally wrap that in the try/catch as you did before.

This all assumes that "c_StreamOutput" is the standard output stream from
the process you started. If you are still having problems with the code
changed to match the above, you should probably post a
concise-but-complete code sample that reliably demonstrates the problem.
That way, we can know exactly what your code is doing and why it does what
it does.

Pete
 
Back
Top