BackgroundWorker组件的使用

using System;
using System.ComponentModel;
using System.Windows.Forms;

namespace BackGroundWorker组件
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            this.backgroundWorker1.DoWork += new DoWorkEventHandler(background1_DoWork);
            this.backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundworker1_ProgressChange);
            this.backgroundWorker1.RunWorkerCompleted+=new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
            this.btnStart.Click += new EventHandler(startAsyncButton_Click);
            this.btnCancel.Click += new EventHandler(btnCancel_Click);
        }

        private int numberToComputer = 0;
        private int highPercentReched = 0;

        private void background1_DoWork(object sender, DoWorkEventArgs e)
        {
            e.Result = ComputeFibonacci((int)e.Argument, this.backgroundWorker1, e);//为组件的运行结果赋值
        }

        long ComputeFibonacci(int n, BackgroundWorker worker, DoWorkEventArgs e)
        {
            if(n<0 || n>91)
            {
                throw new ArgumentException("value must be>=0 and <=91", "n");//抛出异常
            }
            long result = 0;
            if (worker.CancellationPending)
            {
                e.Cancel = true;
            }
            else
            {
                if (n < 2)
                {
                    result = 1;
                }
                else
                {
                    result = ComputeFibonacci(n - 1, worker, e) + ComputeFibonacci(n - 2, worker, e);
                }
                int percentComplete = (int)((float)n / (float)numberToComputer * 100);
                if (percentComplete > highPercentReched)
                {
                    highPercentReched = percentComplete;
                    worker.ReportProgress(percentComplete);
                }
            }
            return result;
        }

        private void backgroundworker1_ProgressChange(object sender, ProgressChangedEventArgs e)
        {
            this.progressBar1.Value = e.ProgressPercentage;//为进度条赋值
        }

        /// <summary>
        /// 当辅助线程完成(无论是成功,失败还是取消)时引发
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void backgroundWorker1_RunWorkerCompleted(object sender,RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                MessageBox.Show(e.Error.Message);
            }
            else if (e.Cancelled)
            {
                resultLabel.Text = "Canceled";
            }
            else
            {
                resultLabel.Text = e.Result.ToString();
            }
            this.numericUpDown1.Enabled = true;
            btnStart.Enabled = true;
            btnCancel.Enabled = false;
        }

        /// <summary>
        /// 开始启用异步操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void startAsyncButton_Click(object sender, EventArgs e)
        {
            resultLabel.Text = string.Empty;
            this.numericUpDown1.Enabled = false;
            this.btnStart.Enabled = false;
            this.btnCancel.Enabled = true;
            numberToComputer = (int)numericUpDown1.Value;
            highPercentReched = 0;
            backgroundWorker1.RunWorkerAsync(numberToComputer);
        }

        /// <summary>
        /// 请求取消后台挂起的操作
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="e"></param>
        private void btnCancel_Click(object obj, EventArgs e)
        {
            this.backgroundWorker1.CancelAsync();
            btnCancel.Enabled = false;
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值