简体   繁体   中英

Progress bar while sql command execute using background worker

I'm trying to create a progress bar wich shown up when the calculate button clicked. And runs until the execute finishes the process. I'm using background worker for the operation. And the progress bar is just a simple marquee so if the process ends i want to torn false the visible property.

here is the initialize

backgroundworker1 = new System.ComponentModel.BackgroundWorker();
        backgroundworker1.DoWork += new System.ComponentModel.DoWorkEventHandler(this.backgroundWorker1_DoWork);
        backgroundWorker1.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.backgroundWorker1_RunWorkerCompleted);

so first when the calculate button clicked:

    private void buttonCalculate_Click(object sender, EventArgs e)
    {
         //execute the background worker 
        this.backgroundworker1.RunWorkerAsync();
        while (this.backgroundworker1.IsBusy)
        {
            progressBar1.Visible=true;
            Application.DoEvents();
        }
    }

Here is the backgroundworker1_DoWork event

 private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            connection = new MySqlConnection(prop.connectionString);
            string query = "Call telephelyi_2013()";

                if (this.OpenConnection() == true)
                {

                    MySqlCommand cmd = new MySqlCommand();
                    cmd = connection.CreateCommand();
                    cmd.CommandText = query;
                    cmd.ExecuteNonQuery();
                }

        }

and finaly when the operation comleeted it shuld be do this

    private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        progressBar1.Visible = false;
        MessageBox.Show("Számítás befejzve!");
    }

But after all when i run the program and click on the calculate button the progress bar shown up and just moving never ends. And i also see that the computer is calculating for a while and after stops but i never get that end message!

whats wrong?

You need to just start the background worker and then let it go, rather than holding up the main thread by waiting on the worker. Using DoEvents is just a hack that is going to cause more problems than it'll solve unless you're very intimately familiar with what it does, how it works, and when you should use it.

Just have your button click do this:

this.backgroundworker1.RunWorkerAsync();
progressBar1.Visible=true;

And voila.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM