首页 > 代码库 > WPF线程——BackgroundWorker

WPF线程——BackgroundWorker

在WPF中第二个常用的线程处理方式就是BackgroundWorker。

以下是BackgroundWorker一个简单的例子。

public partial class MainWindow : Window    {        /// <summary>        /// 后台worker        /// </summary>        BackgroundWorker worker = new BackgroundWorker();        public MainWindow()        {            InitializeComponent();            worker.WorkerReportsProgress = true;            worker.DoWork += new DoWorkEventHandler(worker_DoWork);            worker.ProgressChanged += worker_ProgressChanged;            this.btn_test.Click += btn_test_Click;        }        /// <summary>        /// 按钮点击        /// </summary>        /// <param name="sender"></param>        /// <param name="e"></param>        void btn_test_Click(object sender, RoutedEventArgs e)        {            worker.RunWorkerAsync();        }        /// <summary>        /// 进度返回处理        /// </summary>        /// <param name="sender"></param>        /// <param name="e"></param>        void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)        {            this.pb_test.Value = http://www.mamicode.com/e.ProgressPercentage;>

其中要注意的有BackgroundWorker的属性WorkerReportsProgress表示BackgroundWorker是否可以返回进度。事件DoWork中处理自身的业务逻辑,ProgressChanged负责更新界面操作。

 


项目托管地址:https://wpfthread.codeplex.com/

WPF线程——BackgroundWorker