简体   繁体   中英

using progress bar in background worker

I have 2 forms and at the second form I have a progress bar. When I click a button on the Main Form opens Form2 with progress bar:

private void button1_Click(object sender, EventArgs e)
{
    this.ShowInTaskbar = false;
    this.Visible = false;
    bw.RunWorkerAsync();
    //Show Form2 with progress bar
    Show_pb();
}
Form2 f_pb = new Form2();

Show_pb()
{
    f_pb.ShowDialog();
    f_pb.Activate();
}

private void bw_DoWork(object sender, DoWorkEventArgs e)
{
    //... hard work...
}

After that in bw_RunWorkerCompleted I fill data to some controls in Form1:

void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    //...updating DataGridView and TreeView...
}

Unfortunatelly, when bw_RunWorkerCompleted works, marquee Progress Bar is freezing and it looks like that the app is hanging.

What can I do?

Showing the progress dialog with ShowDialog blocks the UI thread, so there is no way that progress will be updated. The code updating stuff on the UI after the background worker is done can't execute for the same reason.

The way to go is:

  1. Implement the background worker's progress event and have the background worker report progress in this event (this will be called in the context of the UI thread, so you don't have to worry about cross-thread problems)
  2. Make the progress "dialog" a normal window that is topmost and looks like a dialog (you may need to implement further stuff to make sure it can't be deactivated and disable the main window, because it will continue being responsive).
  3. In the progress event handler, update the progress status in the secondary window.

You say now in the comments that your progress bar is actually a marquee, not showing any real progress. Doesn't really matter to the solution - just don't do the progress update stuff.

The thing is that ShowDialog blocks your UI thread until the dialog is closed, which you can not do from your code. Make it a non-modal dialog and you should be fine.

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