In this simple test program, I want to see the text "DONE!" after the progress bar has been filled in 100%. Currently, it displays "DONE!" way before 100% - I am even able to get a screen shot of it. I guess, that the problem is related to Windows' message queue, but even "Application.DoEvents()" before setting the label does not cure the problem. A "Thread.Sleep(500)" will make the problem disappear, but it will also waste half a second of my life ;-) I would like to know WHY the text appears before 100% is reached and what I can do (better than sleep) to avoid it?
private void button1_Click(object sender, EventArgs e)
{
button1.Enabled = false;
label1.Text = "In progress";
label1.Refresh();
int CountDown = 10000;
progressBar1.Value = 0;
progressBar1.Maximum = CountDown;
while (CountDown > 0)
{
CountDown--;
progressBar1.Value = progressBar1.Maximum - CountDown;
progressBar1.Refresh();
}
label1.Text = "DONE!";
button1.Enabled = true;
}
Progress bar not complete yet, but "DONE!" already displayed:
Version 2.0 with updates inspired by Alexandru and Jimi (see comments below)
public partial class Form1 : Form
{
const int cStartCountDown = 1000;
public Form1()
{
InitializeComponent();
backgroundWorker1.WorkerReportsProgress = true;
}
private void button1_Click(object sender, EventArgs e)
{
progressBar1.Value = 0;
progressBar1.Maximum = cStartCountDown;
label1.Text = "In progress";
label1.Refresh();
if (backgroundWorker1.IsBusy != true)
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
int CountDown = cStartCountDown;
while (CountDown > 0)
{
if (worker.CancellationPending == true)
{
e.Cancel = true;
break;
}
else
{
CountDown--;
worker.ReportProgress(CountDown);
}
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = progressBar1.Maximum - e.ProgressPercentage;
// progressBar1.Refresh();
Task wait = Task.Delay(1);
wait.Wait();
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Error != null)
{
label1.Text = "Error: " + e.Error.Message;
}
else
{
label1.Text = "DONE!";
}
}
}