BackgroundWorker异步更新界面

BackgroundWorker类似于线程,但又不太一样,因为线程不可以直接更新界面,而BackgroundWorker可以。代码如下

 private void buttonTest_Click(object sender, EventArgs e)
        {
            BackgroundWorker worker = new BackgroundWorker();
            worker.WorkerReportsProgress = true;
            worker.DoWork += Bw_DoWork;
            worker.ProgressChanged += Bw_ProgressChanged;
            worker.RunWorkerAsync();
        }

        private void Bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            labelProcess.Text = e.ProgressPercentage.ToString();
        }

        private void Bw_DoWork(object sender, DoWorkEventArgs e)
        {
            var worker = sender as BackgroundWorker;
            for (int i = 0; i < 100; i++)
            {
                worker.ReportProgress(i);
                Thread.Sleep(100);
            }
        }
结果如下图



posted @ 2017-07-21 09:26  _学而时习之  阅读(606)  评论(0编辑  收藏  举报