VB.NET simple Async Await example

I scoured the interwebs looking for a VB.NET simple Async Await example, and kind of came up empty. So, I decided to try to use bits and pieces of the examples I could find to roll my own.

The background here is that I am working on an application that accesses resources on the internet, and did not want to block the UI while the communications code was running.

Here is the code that I came up with:

Async Function GetDetails(theID As String) As Task
 
    Dim url As String
    url = GET_DETAILS_URL & "?theid=" & theID
 
    Dim request As WebRequest = WebRequest.Create(url)
    Dim response As WebResponse = Await request.GetResponseAsync()
    Dim dataStream As Stream = response.GetResponseStream()
    Dim reader As New StreamReader(dataStream)
    Dim responseFromServer As String = reader.ReadToEnd()
 
    reader.Close()
    response.Close()
 
    ' do something here with responseFromServer
 
End Function
 
Async Sub lstItems_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lstItems.SelectedIndexChanged
 
    Dim idx As Integer = lstItems.SelectedIndex
 
    ' get the selected item
    Dim theItem As Object = itemsList(idx)
    Dim theItemID As String = theItem.itemID.ToString()
    Await GetDetails(theItemID)
 
End Sub

BTW, Happy Bennington Battle Day to our Green Mountain friends.

Leave a Reply