zoukankan      html  css  js  c++  java
  • 执行异步UI更新

    异步更新UI的几种方法
    ①.使用Control.Invoke方式来更新数据        
                foreach (DataGridViewRow dgvr in this.dgv_selected.Rows)
                {
                    Application.DoEvents();
                    this.progressBar1.Invoke(new MethodInvoker(delegate { this.progressBar1.Maximum = this.dgv_selected.Rows.Count; }));

                    //this.progressBar1.Invoke(new MethodInvoker(delegate { this.label12.Text = "正在保存:" + dgvr.Cells["Column3"].Value.ToString(); }));
                    this.label12.Invoke(new MethodInvoker(delegate { this.label12.Text = "操作进度:" + dgvr.Cells["Column3"].Value.ToString(); }));
                    this.label12.Refresh();

                    this.progressBar1.Invoke(new MethodInvoker(delegate { this.progressBar1.Value++; }));
                 }


    ②.使用委托来更新:
            private delegate void IncreaseProgressBarValue(string username);
            private void updateProgerssBar(string username)
            {
                if (this.progressBar1.InvokeRequired)
                {
                    IncreaseProgressBarValue inc = new IncreaseProgressBarValue(updateProgerssBar);
                    this.progressBar1.Invoke(inc,new object[]{username});
                }
                else
                {
                    this.progressBar1.Value++;
                    this.label12.Text = "查询员工:" + username;
                    this.label12.Refresh();
                }
            }
    使用下面的方式调用委托:
            ThreadStart ts = delegate { updateProgerssBar(dgvr.Cells["EmpName"].Value.ToString()); };
            new Thread(ts).Start();


    ③.在.net framework4.0中使用TaskScheduler来实时更新UI
            private void AsyncWork()
            {
                // This scheduler will execute tasks
                // on the current SynchronizationContext
                // That is, it will access UI controls safely
                var uis = TaskScheduler.FromCurrentSynchronizationContext();
                for (int i = 0; i < 100; i++)
                {
                    Application.DoEvents();
                    Task.Factory.StartNew(() =>
                    {
                        updateProgressBar();
                    }, new CancellationToken(), TaskCreationOptions.None, uis);
                }  
            }
            private void updateProgressBar()
            {
                this.progressBar1.Value++;
                Thread.Sleep(100);
            }

  • 相关阅读:
    Swift3 重写一个带占位符的textView
    Swift3 使用系统UIAlertView方法做吐司效果
    Swift3 页面顶部实现拉伸效果代码
    Swift3 倒计时按钮扩展
    iOS 获取当前对象所在的VC
    SpringBoot在IDEA下使用JPA
    hibernate 异常a different object with the same identifier value was already associated with the session
    SpringCloud IDEA 教学 番外篇 后台运行Eureka服务注册中心
    SpringCloud IDEA 教学 (五) 断路器控制台(HystrixDashboard)
    SpringCloud IDEA 教学 (四) 断路器(Hystrix)
  • 原文地址:https://www.cnblogs.com/goxmpx/p/3337014.html
Copyright © 2011-2022 走看看