进程为 运行 时无法显示文本 c# WPF

Cannot display text while process is running c# WPF

我有一个使用 ST-LINK_CLI.exe.

将固件编程到 ST-LINK 的应用程序

用户选择一个固件,按下开始,过程开始。但是开发板编程需要相当长的时间,用户可能会认为程序崩溃了。我想要一个文本块来显示“Board Programming...”,以便他们知道它正在工作。

但是,目前代码在编程之前不会显示文本,我不确定为什么。以下是我在点击开始按钮事件上的代码:

 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
        {

            try
            {

                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
            finally
            {
                int code = process.ExitCode; //get exit code
                codee = code.ToString(); //set code to string
                File.WriteAllText("Code.txt", codee); //save code
              }

在进程开始 运行 之前或在进程 运行ning 期间,是否有办法让文本显示?

谢谢 露西

问题是,虽然 while 循环是 运行,因为它在主线程中,UI 不会刷新。解决这个问题的正确方法是将 "problematic" 代码放在另一个线程中,使用 Dispatcher or a Background Worker.

或者,您可以将此 programmingTextBlock.Text = "Board Programming..."; 置于 while 循环之外,然后添加此行:

Application.Current.Dispatcher.Invoke(DispatcherPriority.Background,
                                      new Action(delegate { }));

这应该 "refresh" 在进入循环之前 ui。

你说的 Waiting Bar 应该在长时间的执行过程中出现,并在完成后消失。你不是吗? 为此,您应该实施 async/await 模式以防止 UI 线程卡住。 在您的视图模型中:

            this.IsBusy = true;
            await MyTaskMethodAsync();
            this.IsBusy = false;

MyTaskMethodAsync returns Task。 在您的 XAML 中定义您的 Busy Bar 并绑定到 IsBusy 属性 您可以在 C# 代码中看到:

 <Border Visibility="{Binding IsBusy,Converter={converters:BooleanToSomethingConverter TrueValue='Visible', FalseValue='Collapsed'}}"
            Background="#50000000"
            Grid.Row="1">
        <TextBlock Foreground="White"
                   VerticalAlignment="Center"
                   HorizontalAlignment="Center"
                   Text="Loading. . ."
                   FontSize="16" />
    </Border>