Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async/await did not make an asynchronous effect

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
like image 652
Alex.Li - MSFT Avatar asked Jan 01 '23 18:01

Alex.Li - MSFT


2 Answers

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

label1will not change before the 3sec delay is over. your event handler awaits the task, and then continues execution, changing the label. But Async/Awaitdefinitly 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/awaitversion, 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.

like image 169
AConfusedSimpleton Avatar answered Jan 13 '23 14:01

AConfusedSimpleton


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
like image 31
Alex.Li - MSFT Avatar answered Jan 13 '23 15:01

Alex.Li - MSFT