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
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:
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.