time lag problems

starcraft

Centurion
Joined
Jun 29, 2003
Messages
167
Location
Poway CA
why when i add time lag to my program in the code ->
Visual Basic:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        TextBox1.Text = ""
        TextBox1.Text = "5"
      
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        System.Threading.Thread.Sleep(1000)
        TextBox1.Text = "4"
        System.Threading.Thread.Sleep(1000)
        TextBox1.Text = "3"
        System.Threading.Thread.Sleep(1000)
        TextBox1.Text = "2"
        System.Threading.Thread.Sleep(1000)
        TextBox1.Text = "1"
        System.Threading.Thread.Sleep(1000)
        TextBox1.Text = "Finished"
    End Sub
it does modify the textbox1.text to 4/3/2/1 it just waits 5 seconds and puts finished
what do i change?
 
The texbox doesnt have time to print the text becuase it goes to sleep right away so you need to call DoEvents before every sleep so it can finish:
Visual Basic:
textbox1.Text = "5"
Application.DoEvents()
System.Threading.Thread.Sleep(1000)
textbox1.Text = "4"
Application.DoEvents()
System.Threading.Thread.Sleep(1000)
textbox1.Text = "3"
Application.DoEvents()
System.Threading.Thread.Sleep(1000)
textbox1.Text = "2"
Application.DoEvents()
System.Threading.Thread.Sleep(1000)
textbox1.Text = "1"
Application.DoEvents()
System.Threading.Thread.Sleep(1000)
textbox1.Text = "DONE"

Also I suggest that you use timer for this kind of thing, it doesnt require you to put the thread to sleep so your application can respond during that time.
 
Read up on timers in MSDN. There are three types of timer in the framework, you want the Windows Forms one in this case.
 
you could do this :
Visual Basic:
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim i As Integer = 5
        Dim x As Integer

        For x = 1 To 5
            TextBox1.Text = i
            i = i - 1
            Application.DoEvents()
            Threading.Thread.Sleep(1000)
        Next

    End Sub

or better still as Divil says use a timer , eg :
Visual Basic:
Dim x As Integer = 5
' /// made available to all subs ^^^
' ///
    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click

        Dim i As Integer
        TextBox1.Text = x
        For i = 1 To 4
            With Timer1
                .Interval = 1000
                .Enabled = True
                .Start()
            End With
        Next

    End Sub

    Private Sub Timer1_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles Timer1.Tick

        TextBox1.Text = x
        x = x - 1
        If x < 1 Then
            Timer1.Stop()
            x = 5
        End If
    End Sub
 
Back
Top