1

我试图获得一个与等待工作的异步的简单示例,但我认为不是。我认为这段代码应该需要 10 秒(或超过 10 秒)才能运行,因为 for each 循环中的每个函数都应该异步运行。

这是一个 asp.net 网络表单,页面声明中存在 Async="true"。

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

提前致谢!

4

1 回答 1

3

不,它们不会异步运行,因为您在这里说过“在得到结果之前不要继续”:

r1 = Await processAsyncA(10)

您应该做的是启动所有processXXX功能,然后等待所有功能。就像是:

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) & "  "

(不是最干净的代码,但希望你能明白要点)

于 2013-02-21T07:06:41.607 回答