我试图在VB Forms中找到一种等待命令,但是我不希望使用sleep命令,因为它会在执行所有代码之前冻结程序。有什么办法吗?
TextBox1.Text = "0"
' (Code goes here)
TextBox2.Text = "0"
答案 0 :(得分:0)
最简单的答案是使用Async
/ Await
和Task.Delay
。
只需执行以下操作:
Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
TextBox1.Text = "Immediately"
Await Task.Delay(TimeSpan.FromSeconds(2.0))
TextBox1.Text = "Later"
End Sub
请注意,我必须将标准Private Sub Button1_Click
处理程序签名更改为Private Async Sub Button1_Click
。
另一个选择是使用Windows窗体计时器。只需将一个从工具箱拖到您的表单上即可。
然后您可以执行以下操作:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
TextBox1.Text = "Immediately"
Timer1.Interval = 2000
Timer1.Enabled = True
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
TextBox1.Text = "Later"
End Sub
如果要在更新文本之前停止计时器,可以执行以下操作:
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Timer1.Enabled = False
TextBox1.Text = "Stopped"
End Sub