c#中BackGroundWorker控制項

來源:互聯網
上載者:User

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

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.