共用方式為


Async (Visual Basic)

Async 修飾詞表示修改的方法或 Lambda 運算式 是非同步的。 這種方法稱為 非同步方法。

可提供便利的方式進行可能需要長期執行的工作,而不封鎖呼叫端執行緒。 非同步方法的呼叫端可以繼續它的工作,而不需等待非同步方法。

注意事項注意事項

Async 與 Await 關鍵字在 Visual Studio 2012 中引入。如需在該版本的其他新功能的詳細資訊,請參閱 Visual Studio 2012 的新功能

如需非同步程式設計的簡介,請參閱 使用 Async 和 Await 設計非同步程式 (C# 和 Visual Basic)

下列範例會示範非同步方法的結構。 依照慣例,非同步方法名稱以「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 所有的非同步方法,因為這種情況可能表示錯誤。 如需詳細資訊,請參閱 編譯器錯誤

Async 關鍵字是未保留的關鍵字。 會修改方法或 Lambda 運算式時,它是關鍵字。 在其他內容中,則會將它解譯為識別項。

傳回類型

非同步方法是 子函數 程序或有 TaskTask<TResult>的傳回型別 函式 的程序。 方法不可以宣告任何 ByRef 參數。

如果方法的 傳回 陳述式有型別參數,運算元為非同步方法的傳回型別指定 Task(Of TResult) 。 您可以使用 Task ,如果有意義的值未傳回,當方法完成時。 也就是對方法的呼叫傳回,則為 Task,但是,當 Task 完成時,等候 Task 的任何 Await 陳述式未產生結果值。

Async 副程式主要是用來定義需要 Sub 程序的事件處理常式。 非同步副程式的呼叫端不等候它無法攔截方法擲回的例外狀況。

如需詳細資訊與範例,請參閱非同步方法的傳回型別 (C# and Visual Basic)

範例

下列範例顯示一個非同步事件處理常式、非同步 Lambda 運算式和執行非同步方法。 如需使用這些項目的完整範例,請參閱 逐步解說:使用 Async 和 Await 存取 Web (C# 和 Visual Basic)。 您可以下載逐步解說程式碼從 開發人員程式碼範例

' 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

請參閱

工作

逐步解說:使用 Async 和 Await 存取 Web (C# 和 Visual Basic)

參考

Await 運算子 (Visual Basic)

AsyncStateMachineAttribute

概念

使用 Async 和 Await 設計非同步程式 (C# 和 Visual Basic)