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);
            }

  • 相关阅读:
    APIO2019游记
    ZJOI2019赛季回顾
    「HNOI 2019」白兔之舞
    LOJ #6539 奇妙数论题
    BZOJ4314 倍数?倍数!
    伯努利数学习笔记&&Luogu P3711 仓鼠的数学题
    BZOJ 5093[Lydsy1711月赛]图的价值 线性做法
    AtCoder Grand Contest 030题解
    Codeforces Round #542 (Div. 1) 题解
    Codeforces Round #541 (Div. 2)题解
  • 原文地址:https://www.cnblogs.com/goxmpx/p/3337014.html
Copyright © 2011-2022 走看看