簡體   English   中英

簡單的ASP.NET 4.5異步並在VB.NET中等待

[英]Simple ASP.NET 4.5 async and await in VB.NET

我試圖得到一個簡單的異步示例等待工作,但我認為不是。 我認為這段代碼需要花費10秒鍾(或超過10秒鍾)來運行,因為每個循環中的每個函數都應該異步運行。

這是一個asp.net Web表單,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

提前致謝!

不,他們不會異步運行,因為你說“在得到結果之前不要繼續”:

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

(不是最干凈的代碼,但希望你得到的要點)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM