需要在for循环中添加延迟

时间:2019-06-22 09:42:00

标签: vb.net for-loop delay

所以我需要在for循环中添加一个延迟,因为它发生的时间超过了ID,例如延迟大约为1秒

我尝试了Threading.Thread.Sleep(),但是只是延迟了整个表单的打开时间

        For Movement As Integer = 1 To 100
            Invader.SizeMode = PictureBoxSizeMode.StretchImage
            Invader.Width = 53
            Invader.Height = 42
            Invader.Top = 50
            Invader.Left = 50
            Invader.ImageLocation = "D:\.Visual Studio\SSD game\Resources\Invader.png"
            Me.Controls.Add(Invader)
            Invader.Location = New Point(12, 12)
        Next
        Timer1.Enabled = True

1 个答案:

答案 0 :(得分:0)

从Loop内部异步调用了一个延迟函数,该延迟函数应该在方法中。参见下面的代码:


Public Async Sub YourLoopThatWorksAsync()
        For Movement As Integer = 1 To 100
            Invader.SizeMode = PictureBoxSizeMode.StretchImage
            Invader.Width = 53
            Invader.Height = 42
            Invader.Top = 50
            Invader.Left = 50
            Invader.ImageLocation = "D:\.Visual Studio\SSD game\Resources\Invader.png"
            Me.Controls.Add(Invader)
            Invader.Location = New Point(12, 12)

            Dim result as integer = Await ResponsiveSleep()
        Next

End Sub

Public Async Function ResponsiveSleep() As Task(Of Integer)
    Await Task.Delay(1000)  ' 1000ms = 1 sec
    return 1
End Function