开发者

BackgroundWorker and Progressbar.Show()

开发者 https://www.devze.com 2023-01-02 19: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.

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 开发者_Go百科void bgWorker_DoWork(object sender, DoWorkEventArgs e) {
  this.Show();
  ....
}

but nothing shows. Why isn't that working?

thanks bye juergen


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.


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号