共用方式為


異步 (Visual Basic)

修飾 Async 詞表示所修改的方法或 Lambda 運算式 是異步的。 這類方法稱為 異步方法

異步方法提供一種便利的方式,讓您不封鎖呼叫端的線程,即可執行潛在的長時間執行工作。 異步方法的呼叫端可以繼續其工作,而不需要等待異步方法完成。

備註

AsyncAwait 關鍵詞是在 Visual Studio 2012 中引進的。 如需異步程式設計的簡介,請參閱 使用 Async 和 Await 進行異步程序設計

下列範例顯示異步方法的結構。 依照慣例,異步方法名稱結尾為 “Async”。

Public Async Function ExampleMethodAsync() As Task(Of Integer)
    ' . . .

    ' At the Await expression, execution in this method is suspended and,
    ' if AwaitedProcessAsync has not already finished, control returns
    ' to the caller of ExampleMethodAsync. When the awaited task is
    ' completed, this method resumes execution.
    Dim exampleInt As Integer = Await AwaitedProcessAsync()

    ' . . .

    ' The return statement completes the task. Any method that is
    ' awaiting ExampleMethodAsync can now get the integer result.
    Return exampleInt
End Function

關鍵詞修改 Async 的方法通常至少包含一個 Await 運算式或語句。 方法會同步執行,直到到達第一個 Await,此時會暫停,直到等候的工作完成為止。 同時,控件會傳回給 方法的呼叫端。 如果方法未包含 Await 表達式或語句,則方法不會暫停並執行,就像同步方法一樣。 編譯程式警告會提醒您任何未包含 Await 的異步方法,因為這種情況可能會指出錯誤。 如需詳細資訊,請參閱 編譯程序錯誤

關鍵詞 Async 是未保留的關鍵詞。 它是修改方法或 Lambda 運算式時的關鍵詞。 在所有其他內容中,它會解譯為標識符。

傳回型別

異步方法是 Sub 程式,或是具有 或Task<TResult>傳回型別的 TaskFunction 程式。 方法無法宣告任何 ByRef 參數。

如果方法的 Return 語句具有 TResult 類型的作數,您可以指定Task(Of TResult)異步方法的傳回型別。 如果方法完成時未傳回任何有意義的值,則使用 Task。 也就是說,對方法的呼叫會 Task傳回 ,但當 完成時 TaskAwait 任何等候 的 Task 語句都不會產生結果值。

異步子程式主要用於定義需要程式的事件處理程式 Sub 。 異步子程式呼叫端無法等候它,而且無法攔截方法擲回的例外狀況。

如需詳細資訊和範例,請參閱非同步方法的傳回型別

範例

下列範例顯示異步事件處理程序、異步 Lambda 表達式和異步方法。 如需使用這些元素的完整範例,請參閱 逐步解說:使用 Async 和 Await 存取 Web。 您可以從 .NET 範例瀏覽器下載範例。 範例程式碼位於 SerialAsyncExample 專案中。

' An event handler must be a Sub procedure.
Async Sub button1_Click(sender As Object, e As RoutedEventArgs) Handles button1.Click
    textBox1.Clear()
    ' SumPageSizesAsync is a method that returns a Task.
    Await SumPageSizesAsync()
    textBox1.Text = vbCrLf & "Control returned to button1_Click."
End Sub

' The following async lambda expression creates an equivalent anonymous
' event handler.
AddHandler button1.Click, Async Sub(sender, e)
                              textBox1.Clear()
                              ' SumPageSizesAsync is a method that returns a Task.
                              Await SumPageSizesAsync()
                              textBox1.Text = vbCrLf & "Control returned to button1_Click."
                          End Sub

' The following async method returns a Task(Of T).
' A typical call awaits the Byte array result:
'      Dim result As Byte() = Await GetURLContents("https://msdn.com")
Private Async Function GetURLContentsAsync(url As String) As Task(Of Byte())

    ' The downloaded resource ends up in the variable named content.
    Dim content = New MemoryStream()

    ' Initialize an HttpWebRequest for the current URL.
    Dim webReq = CType(WebRequest.Create(url), HttpWebRequest)

    ' Send the request to the Internet resource and wait for
    ' the response.
    Using response As WebResponse = Await webReq.GetResponseAsync()
        ' Get the data stream that is associated with the specified URL.
        Using responseStream As Stream = response.GetResponseStream()
            ' Read the bytes in responseStream and copy them to content.
            ' CopyToAsync returns a Task, not a Task<T>.
            Await responseStream.CopyToAsync(content)
        End Using
    End Using

    ' Return the result as a byte array.
    Return content.ToArray()
End Function

另請參閱