Async/await has no effect,
I think label1 should be executed immediately.
Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Await Task.Run(Sub()
Threading.Thread.Sleep(3000)
End Sub)
Label1.Text = "123"
End Sub
I think you have misunderstood how Async/Await
is supposed to work. in your code:
Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Await Task.Run(Sub()
Threading.Thread.Sleep(3000)
End Sub)
Label1.Text = "123"
End Sub
label1
will not change before the 3sec delay is over. your event handler awaits the task, and then continues execution, changing the label. But Async/Await
definitly has an effect.
compare your code to this one:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
threading.Thread.Sleep(3000)
Label1.Text = "123"
End Sub
the same thing will happen as in your code: after 3secs the label will change. However, there is one huge difference; in your code, the Async/await
version, the UI doesn't block which means you could press another button and the code there would still execute immediatly.
Await
signals that there's a long task going on, and the UI thread will not continue executing the sub
until that task completes (on a different thread). once it does, the UI thread will pick up where it left of and update the label.
It seems the following and the code is more like asynchronous
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim action1 As Action = New Action(Sub()
Threading.Thread.Sleep(3000)
End Sub)
action1.BeginInvoke(Nothing, Nothing)
Label1.Text = "123"
End Sub
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With