1. 程式人生 > >BackgroundWorker非同步更新介面

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);
            }
        }
結果如下圖