鸟语天空
异步操作——BackgroundWorker
post by:追风剑情 2015-10-21 18:09

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace BackGroundWorkerTest
{
    public partial class Form1 : Form
    {
        BackgroundWorker backgroundWorker1 = new BackgroundWorker();

        public Form1()
        {
            InitializeComponent();

            progressBar1.Minimum = 0;
            progressBar1.Maximum = 100;

            backgroundWorker1.WorkerReportsProgress = true;
            backgroundWorker1.WorkerSupportsCancellation = true;
            backgroundWorker1.RunWorkerCompleted += RunWorkerCompleted;
            backgroundWorker1.ProgressChanged += ProgressChanged;
            backgroundWorker1.DoWork += DoWork;
        }

        private void button_start_Click(object sender, EventArgs e)
        {
            if(backgroundWorker1.IsBusy)
                return;
            backgroundWorker1.RunWorkerAsync();
        }

        private void button_cancel_Click(object sender, EventArgs e)
        {
            backgroundWorker1.CancelAsync();
        }

        private void DoWork(object sender, DoWorkEventArgs e)
        {
            //模拟加载
            for (int i = 1; i <= 100; i++)
            {
                Thread.Sleep(100);
                //如果用户取消了操作
                if (backgroundWorker1.CancellationPending)
                {
                    e.Cancel = true;
                    return;
                }

                backgroundWorker1.ReportProgress(i);
            }
        }

        private void ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progressBar1.Value = e.ProgressPercentage;//显示进度
            label_per.Text = e.ProgressPercentage + "%";
        }

        private void RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled)
            {
                MessageBox.Show("操作被取消");
            }
            else
            {
                MessageBox.Show("操作完成");
            }
        }
    }
}

运行效果

BBBBB.png

评论:
发表评论:
昵称

邮件地址 (选填)

个人主页 (选填)

内容