码迷,mamicode.com
首页 > 编程语言 > 详细

c#多线程,进度条,实时给前台发送数据

时间:2018-03-21 20:03:09      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:win   box   int   sys   隐藏   多线程   调用   star   oar   

///做了一个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;   //隐藏

                               }));          
        }

附带效果图:
               技术分享图片

 

c#多线程,进度条,实时给前台发送数据

标签:win   box   int   sys   隐藏   多线程   调用   star   oar   

原文地址:https://www.cnblogs.com/ms1976/p/8618636.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!