2016-08-22 24 views
0

我有一個使用ST-LINK_CLI.exe將固件編程到ST-LINK的應用程序。進程運行時無法顯示文本c#WPF

用戶選擇一個固件,按下啓動按鈕,過程開始。然而,董事會需要相當長的時間進行編程,用戶可能會認爲該程序已經崩潰。我想要一個文本塊來顯示'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 
       } 

有反正去顯示進程開始運行或同時的進程正在運行之前的文本

感謝 ?露西

+0

要操作的用戶界面和做其他事情的時候,您需要使用另一個thred。 – Whencesoever

+0

我該怎麼做呢? – lucycopp

回答

3

問題是因爲while循環正在運行,因爲它在主線程中,UI將不會刷新。解決這個問題的正確方法是使用DispatcherBackground Worker將「問題」代碼置於另一個線程中。

另外,還可以藉此programmingTextBlock.Text = "Board Programming...";while外循環,然後添加這一行:進入循環前

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

這應該「刷新」的用戶界面。

+0

謝謝你完美的作品! – lucycopp

+0

很好用:) – Pikoh

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> 
相關問題