简体   繁体   中英

Progress Bar in Background Worker not loading

I've run into an issue that I can't seem to figure out the solution to, I've read several answers and have gotten as far as knowing that I need a BackgroundWorker Thread to make this solution work, but I'm still running into a bit of an issue.

I have a second form that is a small size and set to center on screen with a ProgressBar Style set to Marquee, there is nothing else on this second form as it is meant to emulate a loading bar.

In my data intensive section of the code, on the main form, where it grabs and parses data from a database I have it written like this:

 GetData()
 {
      bwLoading.RunWorkerAsync();
      //Runs all the processing
      bwLoading.CancelAsync();
 }

The background worker is defined as such below, also on the main form.

 private void bwLoading_DoWork(object sender, DoWorkEventArgs e)
    {
        BackgroundWorker worker = sender as BackgroundWorker;
        frmLoading lb = new frmLoading();
        bool running = true;
        while (running)
        {
            if ((worker.CancellationPending == true))
            {
                lb.Close();
                running = false;
            }
            else
            {
                lb.Show();
            }
        }

    }

The problem I have run into is that with this method it shows the Loading form that contains the progress bar does show up when the data starts getting gathered and process and does disappear when the data load is complete, but the window is empty like it's trying to load, but it doesn't. I can't seem to figure out why this isn't working.

Isn't the background worker creating a separate thread for the Loading form to use? Or is there something else that I'm missing from my reading?

You have to actually report the progress of your background operation using ReportProgress() . This requires you knowing how much percent of your work you have completed.

If you do not report progress, the progress bar will always remain at 0% until your background operation is completed, and disappear afterwards - which is what you are observing.

Edit:

In light of your comment - you are using a marquee style progress bar - I think the problem is here:

 GetData()
 {
      bwLoading.RunWorkerAsync();
      //Runs all the processing
      bwLoading.CancelAsync();
 }

I suspect you execute the GetData() method from the UI thread - that means the UI thread is blocked and the progress bar cannot be updated. Move all your processing to the bwLoading_DoWork method so it is executed on a separate thread and not the UI thread - then your progress bar should get updated. Also remove the bwLoading.CancelAsync() call - this would be used only for cancellation.

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