Windows Phone开发 BackgroundWorker的使用,后台执行代码

BackgroundWorker功能类似于多线程,可以执行耗时操作而不影响UI,用法类似于WebClient,以事件的形式与UI线程通讯,如进度改变,执行完毕。BackgroundWorker还可以在执行过程中取消。范例效果图:

代码:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Threading;
using System.ComponentModel;
using System.Diagnostics;

namespace PhoneApp1
{
    public partial class MainPage : PhoneApplicationPage
    {
        private BackgroundWorker bw;
        public MainPage()
        {
            InitializeComponent();
            bw = new BackgroundWorker();
            bw.WorkerReportsProgress = true;
            bw.WorkerSupportsCancellation = true;
            bw.DoWork += new DoWorkEventHandler(bw_DoWork);
            //后台执行方法
            bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);
            //进度改变方法
            bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
            //事件处理不能在点击按钮时才添加,因为是+=,所以当按钮被点多次时,就会有多个事件处理方法
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {

            if (bw.IsBusy != true)
            {//判断是否繁忙,防止在一次没有执行完时按第二次
                bw.RunWorkerAsync();
            }
        }
        private void bw_DoWork(object sender,DoWorkEventArgs e)
        {//后台执行
            BackgroundWorker worker = sender as BackgroundWorker;
            for (int i = 1; i <= 10; i++)
            {
                if ((worker.CancellationPending == true))
                {//被取消
                    e.Cancel = true;
                    break;
                }
                else
                {
                    System.Threading.Thread.Sleep(500);
                    worker.ReportProgress(i * 10);
                }
            }
        }
        private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {//更新进度
            progressBar1.Value = e.ProgressPercentage;
            textBlock1.Text = e.ProgressPercentage.ToString() + "%";
        }
        private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {//执行完毕或取消

            if (e.Cancelled)
            {//判断被取消还是执行完
                textBlock1.Text = "被取消";
            }
            else
            {
                textBlock1.Text = "执行完毕";
            }
        }

        private void button2_Click(object sender, RoutedEventArgs e)
        {//取消执行
            if (bw.WorkerSupportsCancellation == true)
            {
                bw.CancelAsync();
            }
        }


    }
}

© 2012, 冰冻鱼. 请尊重作者劳动成果,复制转载保留本站链接! 应用开发笔记