In my form, I start things by running an executable file loader.exe
(another project in visual studio) which prints some information on console over time until it terminates. What I want to do is:
I want to read console while it continues executing and display the latest output(percentage with some extra info) in a text box textBoxConsole1
in my form application so that the user can be aware of the progress.
EDIT: Currently, it is a bit complicated. It displays some of the output, then displays additional output and then displays the whole remaining output. Not as same as the loader.exe
does.
In this thread C# Show output of Process in real time
Mr.Passant said:
"This is pretty normal, the process will switch to buffered output when you redirect its output. If it doesn't spit out a lot a text then that buffer doesn't fill up enough to cause it to be flushed. Nothing you can do about it if you can't fix the program's code."
So how much is this "enough" exactly? My Code:
private void buttonConnect_Click(object sender, EventArgs e)
{
Thread findThread = new Thread(findProcedure);
findThread.Start();
}
public void findProcedure()
{
Process process = new Process();
process.StartInfo.FileName = PATH;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.RedirectStandardInput = true;
process.StartInfo.CreateNoWindow = true;
process.OutputDataReceived += new DataReceivedEventHandler((sender, e) =>
{
if (!String.IsNullOrEmpty(e.Data))
{
//textBoxConsole1.Text = e.Data; //Cross-thread validation exception
//use thread safe set method instead
setConsole1(e.Data);
}
});
process.ErrorDataReceived += new DataReceivedEventHandler((sender, e) =>
{
if (!String.IsNullOrEmpty(e.Data))
{
setConsole3(e.Data);
}
});
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
process.WaitForExit();
}
And my thread-safe set method:
public void setConsole1(string str)
{
if (this.textBoxConsole1.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(setConsole1);
this.Invoke(d, new object[] { str });
}
else
{
textBoxConsole1.AppendText(str);
textBoxConsole1.AppendText(Environment.NewLine);
}
}
Error data handler method setConsole3
is the same as setConsole1
but sets to another box.