BackgroundWorker and Progressbar.Show()

2019-08-08 18:33发布

I am using Visual Studio 2010 and C# and try to get my progressbar to show but it doesn't work.

I listen to an event. If it happens I want to do some work and show a progressbar while doing that.

This is what I do:

static void Main(string[] args) {
  ProgressForm form = new ProgressForm();
  new FileWatcher(form).Start();
  Application.Run();
}

ProgressForm:
bgWorker.DoWork += new DoWorkEventHandler(bgWorker_DoWork);
private void bgWorker_DoWork(object sender, DoWorkEventArgs e) {
  this.Show();
  ....
}

but nothing shows. Why isn't that working?

thanks bye juergen

3条回答
兄弟一词,经得起流年.
2楼-- · 2019-08-08 18:59

You cannot use a BGW to display a form, the thread does not have the proper state. You'll have to use a Thread so you can call its SetApartmentState() method to switch it to STA. You also need a message loop on the thread to keep the form alive, that requires a call to Application.Run(). And the form must be created on that thread. Thus:

        var t = new Thread(() => Application.Run(new Form1()));
        t.SetApartmentState(ApartmentState.STA);
        t.Start();

One big issue with this form is that it cannot be owned by any window on your UI thread. Giving it the tendency to disappear behind the window of another application. Also, your UI thread is still dead, its windows will ghost with the "Not Responding" message in their caption bar after a few seconds.

The proper way to do this is the other way around: run the time-consuming code on another thread, a BGW would be a very good choice. The UI thread should display your progress form. BackgroundWorker.ReportProgress is ideal to keep the progress bar updated.

查看更多
贼婆χ
3楼-- · 2019-08-08 19:20

You should not change the UI form background threads. This should be done only from the main thread. You can show a basic progress bar just before you start the background worker and hide it in the background worker RunWorkerCompleted event handler. To report real progress you need an implementation as Giorgi suggested.

查看更多
欢心
4楼-- · 2019-08-08 19:21

In order to report progress from the BackgroundWorker you need to call ReportProgress method from the DoWork event handler and show the progress in handler of BackgroundWorker.ProgressChanged Event

查看更多
登录 后发表回答