Reputation: 3
I am building a board game using VB.net
. My problem is that when I have a timer running (for sprite animation) the rest of my program continues executing. Is there some way to delay the execution of the program until the timer has been disabled?
I have tried using Threading.thread.sleep()
but this only delays the whole process., I assume this is because both the timer and the function that starts it are running on the same thread?
While nextSpace <> endSpace
nextSpace += 1
timerMov.Start()
Threading.Thread.Sleep(timerMov.Interval * 100)
End While
Private Sub mov_Tick(sender As Object, e As EventArgs) Handles timerMov.Tick
curShip.img.Location = New Point(...)
If i = 100 Then
timerMov.Stop()
i = 0
End If
i += 1
End Sub
This results in things occurring before I want them to, i.e the user receives information about the space they have landed on before the animation has completed of them landing on said space.
Thanks for any help :)
Upvotes: 0
Views: 436
Reputation: 39122
Essentially what happens is the timer is started from a while loop inside a subroutine. I want the while loop to wait until the timer has been stopped before looping again.
Get rid of the timer and use Async/Await.
Here is what it'd look like, boiled down to its essence:
Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
' ... possibly more code ...
While nextSpace <> endSpace
nextSpace += 1
For i As Integer = 0 To 100
Await Task.Delay(someDelayIntervalHere)
curShip.img.Location = New Point(...)
Next
End While
' ... possibly more code ...
End Sub
Note that the Sub has been marked with Async
in its declaration line. Inside the loop the Await
line causes it to pause (replacing the Tick event of the Timer), but does so in a way that doesn't cause the interface to freeze up.
Upvotes: 1