user1852051
user1852051

Reputation: 23

UI progressbar bug C#

I have a bug with a progressbar, and I don't know what to do with it.

I have a for cycle (or loop) that runs from 0 to 100, and just reports his progress, and then sleeps 100ms:

private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
    for (int i = 0; i <= 100; i++)
    {
        backgroundWorker.ReportProgress(i);
        Thread.Sleep(100);
    }
}

And in the progresschanged event handler method in addition to some other stuff there are two "if"s:

if (matchProgressBar.Value == 50)
{
    OnHalfTime(); //listBox1.Add("Halftime!");
}
if (matchProgressBar.Value == 100)
{
    OnFullTime(); //listBox1.Add("Full time!");
}

The two "unknown" method is adds a line to a listBox. In the first case: "Halftime!"; and in the second: "Full time!". And after both lines there's the same "Thread.Sleep(5000);" //You know, just because you need some break in halftime :) //

But the problem is that however the listBox1 has already been updated, but the GUI sleeps 5 secs before the progressbar has updated. (So the program stucks at 49% and 99% for 5 secs.)

Question: Can I do something to fix this?

Upvotes: 1

Views: 356

Answers (1)

cbranch
cbranch

Reputation: 4769

You really shouldn't call Sleep() in the UI thread. Consider rearranging things so that you pause and then resume your background thread, if that's the intention.

To force the progress bar to update, call Invalidate() and Update(). Example:

matchProgressBar.Invalidate();
matchProgressBar.Update();

EDIT (clarification for @Servy comment):

Just to be clear, I've provided two alternatives above. The preferred way to resolve the problem is to remove the Sleep() in the UI thread and instead let the background thread be responsible for "pausing" at the appropriate times. The second alternative, using Invalidate() and Update() prior to calling Sleep() in the UI thread, would likely work in this specific instance, but is really a hack and will not hold up well from a maintenance standpoint (i.e., prone to break with future code changes), and has other undesirable attributes as well. If at all possible, please use the first method.

Upvotes: 1

Related Questions