c#多線程,進度條,實時給前台發送數據


///做了一個wpf多線程,在實際場景中利用多線程保證程序不會卡死,性能上有所提高

//啟動線程處理
                Thread thread1 = new Thread(UpdateBtn);
                thread1.IsBackground = true;//設置為后台線程,當主線程結束后,后台線程自動退出,否則不會退出程序不能結束
                thread1.Start();

private void UpdateBtn()
        {
         
          //做時name為datatable循環取值給前台txt追加
               for (int i = 0; i < name.Rows.Count; i++)
               {
                   Action action1 = () =>
               {
                   this.txt.AppendText(name.Rows[i][0].ToString() + "  ");
                   this.txt.AppendText(name.Rows[i][1].ToString() + "  ");
                   this.txt.AppendText(name.Rows[i][2].ToString() + "  ");
                   this.txt.AppendText(name.Rows[i][3].ToString() + "  \r\n");
                   txt.Select(txt.Text.Length, 0);

                   Keyboard.Focus(txt);
               };

                //因為主線程在調用所以調用主線程上的委托
                   this.bfb.Dispatcher.Invoke(
                          new Action(
                              delegate
                              {
                                  var s = Math.Round((float)i / name.Rows.Count * 100, 2) + "%";
                                  this.bfb.Content = s;

                              }));      

                   
                 
                   this.txt.Dispatcher.BeginInvoke(action1);
                   SetprogressBar(i);
                   // 如果不設置等待,會導致程序卡死
                   Thread.Sleep(50);
               }
          
           this.progressBar1.Dispatcher.Invoke(
                           new Action(
                               delegate
                               {
                                   bol = true;
                                   System.Windows.MessageBox.Show("執行完畢");
                                   progressBar1.Visibility = Visibility.Hidden;   //隱藏
                                   bfb.Visibility = Visibility.Hidden;   //隱藏

                               }));          
        }

附帶效果圖:
              

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM