BackgroundWorker使用

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;
using System.IO;

namespace backgroundworker
{
    public partial class Form1 : Form
    {
        BackgroundWorker bgw = new BackgroundWorker();

        public Form1()
        {
            InitializeComponent();
            //绑定Dowork事件
            //bgw.DoWork += Bgw_DoWork;
            bgw.DoWork += backgroundWorker1_DoWork;
            //绑定进度更新事件,需要配合WorkerReportsProgress的属性一起使用
            bgw.ProgressChanged += Bgw_ProgressChanged;
            bgw.WorkerReportsProgress = true;
            //指示是否启用用户停止属性
            bgw.WorkerSupportsCancellation = true;

            bgw.RunWorkerCompleted += Bgw_RunWorkerCompleted;
            this.progressBar1.Maximum = 100;
        }

        private void Bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            //如果用户取消了当前操作就关闭窗口。
            //if (e.Cancelled)
            //{
            //    this.Close();
            //}

            //计算已经结束,需要禁用取消按钮。
            this.btn_Stop.Enabled = false;

            //计算过程中的异常会被抓住,在这里可以进行处理。
            if (e.Error != null)
            {
                Type errorType = e.Error.GetType();
                switch (errorType.Name)
                {
                    case "ArgumentNullException":
                    case "MyException":
                        //do something.
                        break;
                    default:
                        //do something.
                        break;
                }
            }
            MessageBox.Show(e.Result.ToString());
            //计算结果信息:e.Result
            //use it do something.
        }

        /// <summary>
        /// 更新UI界面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Bgw_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            this.progressBar1.Value = e.ProgressPercentage;
        }
        /// <summary>
        /// Bgw_DoWork事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Bgw_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker bgWorker = sender as BackgroundWorker;
            int endNumber = 0;
            if (e.Argument != null)
            {
                endNumber = (int)e.Argument;
            }

            for (int i = 0; i < endNumber; i++)
            {

                Thread.Sleep(10);
                bgWorker.ReportProgress(i);
                e.Result = i;
                //在操作的过程中需要检查用户是否取消了当前的操作。
                if (bgWorker.CancellationPending == true)
                {
                    e.Cancel = true;
                    break;
                }
            }
        }

        private void btn_Start_Click(object sender, EventArgs e)
        {

            FileInfo fi = new FileInfo(@"C:\Users\xiaowei.gong\Desktop\新建文件夹\123.txt");
           MessageBox.Show("创建时间:" + fi.CreationTime.ToString() + "  写入文件的时间" +
            fi.LastWriteTime + "   访问的时间" + fi.LastAccessTime);
            //
            if (bgw.IsBusy)
                return;
            this.progressBar1.Value = 0;
            this.btn_Stop.Enabled = true;
            bgw.RunWorkerAsync(2000);
        }

        private void btn_Stop_Click(object sender, EventArgs e)
        {
            bgw.CancelAsync();
        }
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            // Do not access the form's BackgroundWorker reference directly.
            // Instead, use the reference provided by the sender parameter.
            BackgroundWorker bw = sender as BackgroundWorker;

            // Extract the argument.
            int arg = (int)e.Argument;

            // Start the time-consuming operation.
            e.Result = TimeConsumingOperation(bw, arg);

            // If the operation was canceled by the user,
            // set the DoWorkEventArgs.Cancel property to true.
            if (bw.CancellationPending)
            {
                e.Cancel = true;
            }
        }

        // This event handler demonstrates how to interpret
        // the outcome of the asynchronous operation implemented
        // in the DoWork event handler.
        private void backgroundWorker1_RunWorkerCompleted(
            object sender,
            RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled)
            {
                // The user canceled the operation.
                MessageBox.Show("Operation was canceled");
            }
            else if (e.Error != null)
            {
                // There was an error during the operation.
                string msg = String.Format("An error occurred: {0}", e.Error.Message);
                MessageBox.Show(msg);
            }
            else
            {
                // The operation completed normally.
                string msg = String.Format("Result = {0}", e.Result);
                MessageBox.Show(msg);
            }
        }

        // This method models an operation that may take a long time
        // to run. It can be cancelled, it can raise an exception,
        // or it can exit normally and return a result. These outcomes
        // are chosen randomly.
        private int TimeConsumingOperation(
            BackgroundWorker bw,
            int sleepPeriod)
        {
            int result = 0;

            Random rand = new Random();

            while (!bw.CancellationPending)
            {
                bool exit = false;
                int i = rand.Next(3);
                bw.ReportProgress(i * 10);
                switch (i)
                {
                    // Raise an exception.
                    case 10:
                        {
                            throw new Exception("An error condition occurred.");
                            break;
                        }

                    // Sleep for the number of milliseconds
                    // specified by the sleepPeriod parameter.
                    case 1:
                        {
                            Thread.Sleep(sleepPeriod);
                           
                            break;
                        }

                    // Exit and return normally.
                    case 2:
                        {
                            result = 23;
                            //exit = true;
                            break;
                        }

                    default:
                        {
                            break;
                        }
                }

                if (exit)
                {
                    break;
                }
            }

            return result;
        }

    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值