VB.NET simpler Async Await example

Well, I couldn’t let this rest, so here is an even simpler example of doing Async Await in VB.NET.

For this example code, I created a simple forms application with two buttons named cmdSynchronous and cmdAsynchronous, a label called lblStatus, and just to demonstrate the UI locking up effect, a combo box with some entries in it. Here is the code behind this form:

Public Class Form1

    Sub LongOperation()


    End Sub

    Private Sub cmdSynchronous_Click(sender As Object, e As EventArgs) Handles cmdSynchronous.Click

        lblStatus.Text = "Running a long operation synchronously... (UI thread should lock up)"
        Application.DoEvents()  ' needed here so that the label will update


        lblStatus.Text = "Done running the long operation synchronously."

    End Sub

    Private Async Sub cmdAsynchronous_Click(sender As Object, e As EventArgs) Handles cmdAsynchronous.Click

        lblStatus.Text = "Running a long operation asynchronously... (UI thread should be fully responsive)"

        Await Task.Run(Sub()
                       End Sub)

        lblStatus.Text = "Done running the long operation asynchronously."

    End Sub

End Class

Notice that both button click events call the LongOperation method, which just sleeps for 5 seconds. However, the synchronous button click will lock up the UI (try to open the combo box, you will see that it waits until the sleep is done before displaying the choice list), whereas the asynchronous one will not.

Now in general, you would probably want to keep the tasks from piling up, as they would if you keep clicking the asynchronous button. I leave this as an exercise to the reader on preventing this problem.

BTW, Happy Birthday to Gary Hoey and Terje Rypdal, two of my favorite guitarists.

10 thoughts on “VB.NET simpler Async Await example”

  1. Thank you! I’ve been trying to figure out a way for the past several days to modify an existing large project to make a long recursive task asynchronous. This is an incredibly simple solution!

  2. Thank you for a simple example with a nice reusable pattern. So many examples out there include additional complexity that, while nice, is completely unnecessary for the purpose of the example.

  3. Fabuleux de simplicité.
    Merci pour ce modèle de programmation on ne peut plus aisé.

  4. Thank you a million times over. After days of searching along with a lot of trial and error, you’ve proven that less is more.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.