BackgroundWorker and Progressbar.Show()

限于喜欢 提交于 2019-12-11 14:05:03

问题


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


回答1:


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.




回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/3012795/backgroundworker-and-progressbar-show

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!