XardasLord
XardasLord

Reputation: 1937

How to sync ProgressBar in a loop

I try to sync progress bar in a loop with filling label consecutive digits. But my label finishes earlier than progress bar. The picture below shows that situation.

enter image description here

I use second thread to do this long process. Here is my test code:

Public Class Form1

    Dim watek As System.Threading.Thread

    Public Sub New()
        InitializeComponent()
        Control.CheckForIllegalCrossThreadCalls = False
    End Sub


    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        watek = New System.Threading.Thread(AddressOf DoSomething)
        watek.Start()
    End Sub


    Private Sub DoSomething()
        Dim i As Integer = 0
        Dim max As Integer = 10000
        ProgressBar1.Maximum = max
        ProgressBar1.Step = 1

        Do Until i > ProgressBar1.Maximum
            ProgressBar1.PerformStep()
            Label1.Text = i
            i = i + 1
        Loop
    End Sub
End Class

And here is my question - why is it happening? Why progress bar is not sync with label? Please can anyone explain me this? How to get expected result?

Upvotes: 0

Views: 1217

Answers (2)

user3779606
user3779606

Reputation: 49

one thing you can do here is check if the maximum value of progress bar is coming in the label or not and if it is coming and still the value is not being displayed as it should then just write "this.Refresh();" this will force show the changes on UI.

Upvotes: 3

Roy van der Velde
Roy van der Velde

Reputation: 220

A progressbar always needs some "refresh" time.

You can set the value of a Progressbar to a thousand, it needs about 2 seconds to fill up al the way to that value.

Try this:

For i = 0 to max
    ProgressBar1.PerformStep()
    If (i mod 100) = 0 Then
        Application.Doevents()
    End If
Next

Note: i don't condone your way if coding (Control.CheckForIllegalCrossThreadCalls = False) but thats not the issue right now

Upvotes: 1

Related Questions