1. 程式人生 > >BackgroundWorker改變WPF進度條值

BackgroundWorker改變WPF進度條值

 public partial class UpdateWindow
{
        private BackgroundWorker _work=new BackgroundWorker();

        /// <summary>
        /// 建構函式
        /// </summary>
        public UpdateWindow()
        {
            _work.DoWork += new DoWorkEventHandler(doWorkExecute);
            _work.ProgressChanged += new ProgressChangedEventHandler(_work_ProgressChanged);
            _work.RunWorkerCompleted += new RunWorkerCompletedEventHandler(_work_RunWorkerCompleted);
            _work.RunWorkerAsync();//開始執行後臺操作 
            _work.WorkerSupportsCancellation = true;
            _work.WorkerReportsProgress = true;
        }

        private BackgroundWorker worker = null;
		private int count=100;
        public void doWorkExecute(object sender, DoWorkEventArgs e)
        {
           worker = sender as BackgroundWorker;
			for (int i = 0; i < count; i++)
			{
			   //執行非同步dowork
				worker.ReportProgress((i+1) * 100 / count);//完成進度 
			}
        }

        //改變進度條值
        private void _work_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
			//ProgressBar1為WPF中進度條name
            ProgressBar1.Value = e.ProgressPercentage;
        }

        private void _work_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
           //非同步執行完執行的操作
        }

}