Search code examples
c#progress-barbackgroundworker

How to put method in Backgroundworker


I have made a method and i wanted it to put it on Backgroundworker with a progressbar in it. this is the first that im working on a Background worker.

here is my Code:

    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(" ", " ");
                }
            }
        }
    }

Solution

  • Let's assume you have your background worker as a class member:

    private BackgroundWorker bw;
    

    When you are going to use it, you create and initialize it:

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

    Then you start it:

            bw.RunWorkerAsync();
    

    You should provide a method to do actual work:

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

    You might also provide a method to handle percentage change. It will be called automatically whenever you do ReportProgress on your background worker. Be careful, it gets launched in its own thread, not on your UI thread as you might expect:

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