This is what I’ve tried so far:
-
Put
button.Visible = falseinto my form’s initializer and putbutton.Visible = trueto the end of my backgroundWorkers’s DoWork event.
This causes the program to freeze after the BackgroundWorker does its work.
I don’t understand why. -
Put
button.Visible = falseinto my form’s initializer and putbutton.Visible = trueafter mybackgroundWorker1.RunWorkerAsync()call.
This doesn’t work correctly because it displays the button right after the BackgroundWorker starts its work.
I do understand why this is happening. - Put
button.Visible = falseanddoneEvent = new AutoResetEvent(false)into my form’s initializer, then putdoneEvent.WaitOne()andbutton.Visible = trueafter mybackgroundWorker1.RunWorkerAsync()call.
This way, everything works fine except that the ProgressBar I have in my form stops working correctly (it doesn’t show progress until all the work is finished).
I might have an intuitive idea on why this is happening, but I don’t really understand it and I don’t know how to solve it.
You should not call any method/property on your button while your code runs inside the DoWork event because this code is in a different thread than the thread where the button has been created.
The BackgroundWorkwer use a well defined set of events to handle situations where you need to update your interface and you should use these events for that task.
For example you could set the property
WorkerReportsProgressto true, subscribe to the eventProgressChangedand callbackgroundWorker1.ReportProgress(...);inside the DoWork event to update your interface while your background work progress.In your case probably you need to subscribe to the event
RunWorkerCompletedand show your button in that eventIn the link to the MSDN page for BackgroundWorker there is a sample that demonstrate how to update a progress bar while the DoWork event runs a complex task.