lucycopp lucycopp - 3 months ago 25
C# Question

Cannot display text while process is running c# WPF

I have an application which programs firmware to an ST-LINK using ST-LINK_CLI.exe.

The user chooses a firmware, presses start and the process begins. However it takes quite a while for the board to program and the user may think that the program has crashed. I want a text block to display 'Board Programming..." so that they know it is working.

However, at the moment the code doesn't display the text until it has already been programmed and I'm not sure why. The following is my code on the click start button event:

ProcessStartInfo start = new ProcessStartInfo(); //new process start info
start.FileName = STPath; //set file name
start.Arguments = "-C -ME -p " + firmwareLocation + " -v -Run"; //set arguments
start.UseShellExecute = false; //set shell execute (need this to redirect output)
start.RedirectStandardOutput = true; //redirect output
start.RedirectStandardInput = true; //redirect input
start.WindowStyle = ProcessWindowStyle.Hidden; //hide window
start.CreateNoWindow = true; //create no window

using (Process process = Process.Start(start)) //create process


while (process.HasExited == false) //while open
process.StandardInput.WriteLine(); //send enter key
programmingTextBlock.Text = "Board Programming...";

using (StreamReader reader = process.StandardOutput) //create stream reader
result = reader.ReadToEnd(); //read till end of process
File.WriteAllText("File.txt", result); //write to file

catch { } //so doesn't blow up
int code = process.ExitCode; //get exit code
codee = code.ToString(); //set code to string
File.WriteAllText("Code.txt", codee); //save code

Is there anyway to get the text to display before the process begins to run or whilst the process is running?



The problem is that while the while loop is running, as it is in the main thread, the UI is not going to refresh. The right way of solving this is putting the "problematic" code in another thread, using a Dispatcher or a Background Worker.

Alternately, you could take this programmingTextBlock.Text = "Board Programming..."; outside the while loop and then add this line:

                                      new Action(delegate { }));

This should "refresh" the ui before entering the loop.