如何将方法放入 Backgroundworker

How to put method in Backgroundworker

我做了一个方法,我想把它放在 Backgroundworker 上,里面有一个进度条。这是我第一次在后台工作。

这是我的代码:

    public void WorkLoad()
    {
        string conStr, sheetName;
        conStr = string.Empty;
        //Get the name of the First Sheet.

        using (OleDbConnection kuneksyon = new OleDbConnection(Excel07ConString))
        {
            using (OleDbCommand utos = new OleDbCommand())
            {
                using (OleDbDataAdapter oda = new OleDbDataAdapter())
                {
                    utos.Connection = kuneksyon;
                    kuneksyon.Open();
                    DataTable dtExcelSchema = kuneksyon.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                    sheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
                    kuneksyon.Close();
                    DataTable dt = new DataTable();
                    utos.Connection = kuneksyon;
                    utos.CommandText = "SELECT [Engineer],[SITEID],[SITE NAME],[2G TX Status],[3G TX Status],[WO Status-LTE]  From [" + sheetName + "]";
                    kuneksyon.Open();
                    oda.SelectCommand = utos;
                    oda.Fill(dt);
                    kuneksyon.Close();
                    //Populate DataGridView.
                    ForIssuanceView.DataSource = dt;
                    ForIssuanceView.Columns.Add(" ", " ");
                }
            }
        }
    }

假设您的后台工作人员是 class 成员:

private BackgroundWorker bw;

当您要使用它时,您创建并初始化它:

        bw = new BackgroundWorker();
        bw.WorkerReportsProgress = true;
        bw.ProgressChanged += ProgressChanged;
        bw.DoWork += DoWork;

那你开始吧:

        bw.RunWorkerAsync();

你应该提供一个方法来做实际工作:

    private static void DoWork(object sender, DoWorkEventArgs e)
    {
        // do your actual work and report percentage whenever you find appropriate
        for (var p = 0; p < 100; p++)
        {
            bw.ReportProgress(p);
        }
    }

您还可以提供一种方法来处理百分比变化。每当您对后台工作人员执行 ReportProgress 时,它都会自动调用。请注意,它是在自己的线程中启动的,而不是您可能期望的 UI 线程:

    private static void ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        // inform the UI that the percentage has been changed
    }