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

c#中BackGroundWorker控件使用实例

Posted on 2011-04-07 23:45  moss_tan_jun  阅读(825)  评论(1编辑  收藏  举报

一、BackGroundWorker工作步骤

1.向窗体中拖入一个BackGroundWorker控件。

2.在某个方法或者事件中,调用BackGroundWorker的RunWorkerAsync()方法。

3.该方法为异步操作,将自动引发BackGroundWorker的DoWork事件。

4.调用ReportProgress方法将引发ProgressChanged事件。

二、一个使用了BackGroundWorker的例子

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

using System.Threading;
using System.Data.SqlClient;


//该用例需要一个名为bgwTestDB的Sql Server数据库
//数据库中应包含tbBgwTest表。
//表中有data1、data2两列。
//数据库中还需要一个存储过程,sql语句如下:
/***************
create procedure insertOneData
@data1 nchar(10),
@data2 int
as
insert into tbBgwTest (data1,data2) values (@data1, @data2)
********************/

 

 

namespace winBackgroundWorkerTest
{
    public partial class backgroundWorkerTest : Form
    {
        int count = 30;

        public backgroundWorkerTest()
        {
            InitializeComponent();
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            //1.调用bgwInsertData的RunWorkerAsync方法,用来引发DoWork事件
            bgwInsertData.RunWorkerAsync(count);
        }

        private void bgwInsertData_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            //2.在DoWork中调用自定义函数,并将引发DoWork事件的sender传递出去
            insertData(worker);
        }

        private void bgwInsertData_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progressBar1.Value = e.ProgressPercentage;
        }

        //自定义函数 insertData()
        private void insertData(BackgroundWorker worker)
        {
            SqlConnection conn = new SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=bgwTestDB;Integrated Security=True");

            SqlCommand cmd = new SqlCommand("insertOneData", conn);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add("data1", SqlDbType.NChar, 10);
            cmd.Parameters.Add("data2", SqlDbType.Int);

            for (int i = 0; i < count; i++)
            {
                try
                {
                    conn.Open();
                    cmd.Parameters["data1"].Value = i + 1;
                    cmd.Parameters["data2"].Value = i + 1;
                    cmd.ExecuteNonQuery();

                    //3.调用worker的ReportProgress函数,用来引发事件ProgressChanged
                    worker.ReportProgress(i, worker);
                }
                catch(Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                        conn.Close();
                }

                Thread.Sleep(50);
            }
        }

        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);
        }
    }
}