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

时间:2016-08-22 09:42:47

标签: c# wpf process

我有一个使用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
              }

在流程开始运行或流程运行之前,是否要显示文本?

由于 露

2 个答案:

答案 0 :(得分:3)

问题是当while循环正在运行时,就像它在主线程中一样,UI不会刷新。解决这个问题的正确方法是使用DispatcherBackground Worker将“有问题”的代码放在另一个帖子中。

或者,您可以在programmingTextBlock.Text = "Board Programming...";循环之外使用此while,然后添加以下行:

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

这应该在进入循环之前“刷新”ui。

答案 1 :(得分:1)

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

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

MyTaskMethodAsync返回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>
相关问题