Tundra
Tundra

Reputation: 13

VB.NET - When a button is pressed, do an action, wait a few seconds, and do another action

I want to make it so when I press the button, it performs an action, waits a little bit and do another action. However, when I do this it doesn't do the first action until the Sleep has finished. I have also tried making a Background Thread but it can't access the ListBox. Can someone please explain how I can do this, and why my current one doesn't work? Thank you.

Private Sub Button10_Click(sender As Object, e As EventArgs) Handles Button10.Click
    ListBox1.Items.Add("Thing1")
    Threading.Thread.Sleep(500)
    ListBox1.Items.Add("Thing2")


End Sub

Upvotes: 1

Views: 855

Answers (1)

sstan
sstan

Reputation: 36473

it doesn't do the first action until the Sleep has finished

Not exactly. The action does happen, but the UI doesn't reflect the change until the UI thread becomes available to repaint the UI. However, because you put the UI thread to sleep, this does not happen.

Instead of sleeping, use Task.Delay, which works similarly to a sleep, but the UI thread remains free to perform other work, including refreshing the UI:

Private Async Sub Button10_Click(sender As Object, e As EventArgs) Handles Button10.Click
    ListBox1.Items.Add("Thing1")
    Await Task.Delay(500)
    ListBox1.Items.Add("Thing2")
End Sub

Notice that for this to work, you need to add Async to the method signature, and Await to the call to Task.Delay().

To understand how the above code works, you may want to read Asynchronous Programming with Async and Await (Visual Basic).

Upvotes: 3

Related Questions