sqlchris
sqlchris

Reputation: 46

Simple ASP.NET 4.5 async and await in VB.NET

I am trying to get a simple example of async with await working but I don't think it is. I am thinking this code should take 10 seconds (or just over 10 seconds) to run as each function within the for each loop is supposed to run asynchronously.

This is an asp.net web forms and Async="true" is present in the page declaration.

Inherits System.Web.UI.Page

Protected Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    'This needs to execute different asynchronous processes based on the array value
    Dim ItemList(2) As String

    ItemList(0) = "A"
    ItemList(1) = "B"
    ItemList(2) = "C"

    Dim time_start As DateTime
    Dim time_end As DateTime

    Dim r1 As String
    Dim r2 As String
    Dim r3 As String

    'capture start time
    time_start = DateTime.Now

    'run async processes for each item in array
    For Each element As String In ItemList
        Select Case element
            Case "A"
                r1 = Await processAsyncA(10) & "  "
            Case "B"
                r2 = Await processAsyncB(10) & "  "
            Case "C"
                r3 = Await processAsyncC(10) & "  "
        End Select
    Next

    'capture end time
    time_end = DateTime.Now

    'display total duration in seconds
    Label1.Text = DateDiff(DateInterval.Second, time_start, time_end)

End Sub

Protected Async Function processAsyncA(ByVal waittime As Integer) As Task(Of String)
    Await Task.Delay(waittime * 1000)
    Return waittime.ToString
End Function

Protected Async Function processAsyncB(ByVal waittime As Integer) As Task(Of String)
    Await Task.Delay(waittime * 1000)
    Return waittime.ToString
End Function

Protected Async Function processAsyncC(ByVal waittime As Integer) As Task(Of String)
    Await Task.Delay(waittime * 1000)
    Return waittime.ToString
End Function

Thanks in advance!

Upvotes: 1

Views: 7522

Answers (1)

Damien_The_Unbeliever
Damien_The_Unbeliever

Reputation: 239824

No, they won't run asynchronously because you've said "don't carry on until you've got the result" here:

r1 = Await processAsyncA(10)

What you should instead do is launch all of the processXXX functions and then await all of them. Something like:

Dim l as New List(Of Task(Of String))

'run async processes for each item in array
For Each element As String In ItemList
    Select Case element
        Case "A"
            l.Add(processAsyncA(10))
        Case "B"
            l.Add(processAsyncB(10))
        Case "C"
            l.Add(processAsyncC(10))
    End Select
Next

r1 = Await l(0) & "  "
r2 = Await l(1) & "  "
r3 = Await l(2) & "  "

(Not the cleanest code, but hopefully you get the gist)

Upvotes: 3

Related Questions