Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Wait until progressbar finished drawing [duplicate]

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!

like image 400
janw Avatar asked Aug 23 '11 11:08

janw


2 Answers

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;
like image 71
fjdumont Avatar answered Sep 30 '22 02:09

fjdumont


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.

like image 31
Jack Bolding Avatar answered Sep 30 '22 01:09

Jack Bolding