Possible Duplicate:
Winforms Progress bar Does Not Update (C#)
First time asking a question here for me.
I'll try to explain my problem using this code snippet:
progressBar1.Maximum = 50;
for (int i = 0; i < 50; i++)
{
progressBar1.Value++;
}
MessageBox.Show("Finished");
progressBar1.Value = 0;
The problem with this code is that the MessageBox pops up at the time the for loop is finished, not when the progressbar has finished drawing. Is there any way to wait until the progressbar has finished drawing before continuing?
Thanks guys!
You might want to have a look at System.Windows.Forms.Application.DoEvents()
. Reference
progressBar1.Maximum = 50;
for (int i = 0; i < 50; i++)
{
progressBar1.Value++;
Application.DoEvents();
}
MessageBox.Show("Finished");
progressBar1.Value = 0;
The issue here is that you are doing all of your work on the UI thread. In order to re-draw the UI, you would normally need to pump windows messages.The simplest way to fix this would be to tell the progress bar to update. Calling Control.Update will force any pending drawing to be completed synchronously.
progressBar1.Maximum = 50;
for (int i = 0; i < 50; i++)
{
progressBar1.Value++;
progressBar1.Update();
}
MessageBox.Show("Finished");
progressBar1.Value = 0;
The other methods that may work would be to use a background thread (with all of the extra Control.Invoke calls needed to synchronize back to the UI thread). DoEvents (as mentioned previously) should also work -- DoEvents will allow your window to process messages again for a time which may allow your paint messages through. However, it will pump all of the messages in the message queue so it may cause unwanted side effects.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With