-1

I've got a program with a progress bar that doesn't update until the program is finished. I did some digging and figured out that I need to make a background worker so that it will update as my while loop runs. From the examples shown I'm just not getting what I'm supposed to do. Can someone explain to me how to set this up and what it is doing please?

int progressBar;

private void button3_Click(object sender, EventArgs e)
        {

            try
            {
                while (y < PriDID.Count)
                {
                    cmd.CommandText = "SELECT COUNT(*) FROM Accounts WHERE ACCT='" + ACCT[y] + "'";
                    int count = Convert.ToInt32(cmd.ExecuteScalar());

                    if (count < 1)
                    {
                        progressBar = (y / SDM_ACCT.Count) * 100;
                        progressBar1.Value = progressBar;
                        progressBar1.Update();
                        Console.WriteLine(SDM_ACCT[y - 1]);
                        cmd.CommandText = @"INSERT INTO Accounts(SDM_ACCT,Description) 
                                        values(" + "'" + ACCT[y] + "'," + "'" + Comment[y] + ")";
                        cmd.ExecuteNonQuery();
                        y++;
                        recordCount++;
                    }
                    else
                    {
                        y++;
                    }


                    MessageBox.Show(recordCount + " unique records successfully loaded to the Database.");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Exception: " + ex.Message + " Please make sure you have selected a valid path for your CSV and database.");
            }

        }
B Minster
  • 331
  • 3
  • 16
  • What information did you find on how to write a background worker, and what specific problems did you have with your implementation of it? – Servy Mar 01 '17 at 19:49
  • I found this but I just don't understand how to adapt this to what I have. http://stackoverflow.com/questions/6481304/how-to-use-a-backgroundworker – B Minster Mar 01 '17 at 19:51
  • 1
    What *specific* problems did you have adapting it to your situation? What didn't work for you? – Servy Mar 01 '17 at 19:51
  • just push a thread through, or do some research, whichever. – vipersassassin Mar 01 '17 at 19:52
  • I don't understand where to put `void worker_DoWork(object sender, DoWorkEventArgs e)` in order to get it to work properly. – B Minster Mar 01 '17 at 20:10
  • Add `BackgroundWorker` component to your `Form`, using Designer. Find the `DoWork` event in the property grid for the component. Double-click, and the Designer will insert the necessary event handler method. Move the code above from the `Click` event handler method to the `DoWork` event handler method. In the `Click` event handler, just call `RunWorkerAsync()` on your `BackgroundWorker` component. – Peter Duniho Mar 01 '17 at 21:17
  • For progress-bar interaction, set `WorkerReportsProgress = true`, double-click the `ProgressChanged` event in the property grid, add your code to update the progress bar there, and in your `DoWork` handler, call `ReportProgress()` to have the `ProgressChanged` event raised with the progress data you pass to the method. – Peter Duniho Mar 01 '17 at 21:17
  • Or use `Task.Run()` and `Progress` together, to implement all of this in the modern idiom. The two techniques are equivalent, but using `Task.Run()` is compatible with `async`/`await`, which can make the rest of the code easier to write and read. – Peter Duniho Mar 01 '17 at 21:18

1 Answers1

1

I think if you look at this example you will know how you can do it. I made up some values and named the variables same as you. If you know how long it takes for the while loop to run you can declare a DoWork only write this ---> progressBarWorker.DoWork+= and double tab. And you get an DoWork evenhandler. And in that eventhandler you can make a for-loop)

for(int i = 0; i < 100; i++)

{

Thread.Delay(100);

progressBarWorker.ReportProgress(i);

}

and then put ProgressBarWorker.RunWorkerAsync(); as the first thing in the button3 eventhandler.

A BackroundWorker Example I made for you

Mr Tangjai
  • 153
  • 2
  • 9
  • Getting an error "This BackgroundWorker states that it doesn't report progress. Modify WorkerReportsProgress to state that it does report progress." What did I miss? – B Minster Mar 01 '17 at 22:35
  • You have to set the ProgressBarWorker.WorkerReportsProgress = true; – Mr Tangjai Mar 01 '17 at 22:51
  • Ok, this example gave me a progress bar that works intermittently. Sometimes I get an error on `progressBarWorker.ReportProgress(y);` that says "This operation has already had OperationCompleted called on it and further calls are illegal." even if it's the first time trying to run the program. – B Minster Mar 02 '17 at 15:09
  • It depends on what value you set to the "progressBarWorker.Maximum". when you "ReportProgress" and that value is the same as the "Maximum" it will cause the RunWorkerCompleted event to be raised and the BackroundWorker is finished. – Mr Tangjai Mar 02 '17 at 18:10