博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

BackgroundWorker 使用

Posted on 2011-04-11 22:07  moss_tan_jun  阅读(254)  评论(0编辑  收藏  举报

 

Form1

=====================

 

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 ClassLibrary1;

namespace WindowsForms
{
    public partial class Form4 : Form
    {
        int count = 400;

        public Form4()
        {
            InitializeComponent();
        }

        private void Form4_Load(object sender, EventArgs e)
        {
            this.progressBar1.Maximum = count;
        }

     

        private void button1_Click(object sender, EventArgs e)
        {
            bgwInsertData.RunWorkerAsync(count);
        }

        private void bgwInsertData_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            Class1 c1 = new Class1();
            c1.insertData(worker,count);
        }

        private void bgwInsertData_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            this.progressBar1.Value = e.ProgressPercentage;
            this.label1.Text = e.UserState.ToString() + "/" + count.ToString();

        }

        private void bgwInsertData_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                MessageBox.Show(e.Error.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            else if (e.Cancelled)
            {
                MessageBox.Show("取消操作!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            else
                MessageBox.Show("操作成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }
}

 

=================ClassLibrary========

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Threading;

using System.ComponentModel;

namespace ClassLibrary1
{
    public class Class1
    {
        public void insertData(BackgroundWorker worker,int k)
        {
          

            for (int i = 1; i <= k; i++)
            {
                //worker.ReportProgress(i, worker);
               worker.ReportProgress(i * 100 / 100, i);
                Thread.Sleep(50);
            }
        }

    }
}