Process & OutputDataReceived Handler

R

rob

Hello,

I have a DOS program that I need to execute from a WinForm application.
This DOS program will take a long time to execute. During execution it
prints out messages. While the DOS program is still running I want to
catch these messages and display them to the user. I managed to create
the process and redirect the output. The problem I am having is that
the even handler for OutputDataReceived is not called until the DOS
program is finished. Once it is finished the handler gets called for
each line. My question is why does it not get called right after each
line is printed? What am I doing wrong.

Bellow is a sample code. The DOS program prints out one line (with \n")
of random numbers every every 500ms. Proc is a function that is called
when I press a button on the WinForm.

StringBuilder Output;
static int numOutputLines=0;
private void Proc()
{
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
output.Output = new StringBuilder("");
p.OutputDataReceived += new
DataReceivedEventHandler(OutputHandler);

p.StartInfo.FileName = @"randomNum.exe";
p.StartInfo.CreateNoWindow = true;
p.Start();

p.BeginOutputReadLine();
while (true)
{
string s;
s = "";
int n;

//Shows empty string until process is finished
//When process is finished it shows all lines.
s = Output.ToString();
MessageBox.Show(s, "result");
}
p.Close();
}

private void OutputHandler(object sendingProcess,
DataReceivedEventArgs outLine)
{
//This event handler is not called until process is finished.
//When process is finished it gets called once for each line
if (!String.IsNullOrEmpty(outLine.Data))
{
numOutputLines++;
Output.Append(Environment.NewLine +
"[" + numOutputLines.ToString() + "] - " + outLine.Data);
}
}

Regards,
Rob
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top