Async (Visual Basic)Async (Visual Basic)

Async 修飾詞表示它修改的方法或lambda 運算式是非同步。The Async modifier indicates that the method or lambda expression that it modifies is asynchronous. 這類方法稱為「非同步方法」。Such methods are referred to as async methods.

非同步方法提供了方便進行可能需要長時間執行之工作的方式,而不需封鎖呼叫端的執行緒。An async method provides a convenient way to do potentially long-running work without blocking the caller's thread. 非同步方法的呼叫端可以繼續其工作,而不需要等待非同步方法完成。The caller of an async method can resume its work without waiting for the async method to finish.

注意

AsyncAwait 關鍵字是在 Visual Studio 2012 中引入。The Async and Await keywords were introduced in Visual Studio 2012. 如需非同步程式設計的簡介,請參閱使用 async 和 Await 進行非同步程式設計For an introduction to async programming, see Asynchronous Programming with Async and Await.

以下範例將示範非同步方法的結構。The following example shows the structure of an async method. 依照慣例,非同步方法的名稱會以 "Async" 結尾。By convention, async method names end in "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運算式或語句。Typically, a method modified by the Async keyword contains at least one Await expression or statement. 方法會以同步方式執行,直到達到第一個 Await,此時它會暫止,直到等候的工作完成。The method runs synchronously until it reaches the first Await, at which point it suspends until the awaited task completes. 同時,控制權會返回方法的呼叫端。In the meantime, control is returned to the caller of the method. 如果方法不包含 Await 運算式或語句,則方法不會暫止,而且會以同步方法執行。If the method doesn't contain an Await expression or statement, the method isn't suspended and executes as a synchronous method does. 編譯器警告會對未包含 Await 的任何非同步方法發出警示,因為這種情況可能表示發生錯誤。A compiler warning alerts you to any async methods that don't contain Await because that situation might indicate an error. 如需詳細資訊,請參閱編譯器錯誤For more information, see the compiler error.

Async 關鍵字是未保留的關鍵字。The Async keyword is an unreserved keyword. 它是修飾方法或 Lambda 運算式時的關鍵字。It is a keyword when it modifies a method or a lambda expression. 在所有其他內容中,它會解譯為識別項。In all other contexts, it is interpreted as an identifier.

傳回型別Return Types

非同步方法可以是Sub程式,或是傳回類型為 TaskTask<TResult>的函式程式。An async method is either a Sub procedure, or a Function procedure that has a return type of Task or Task<TResult>. 方法無法宣告任何ByRef參數。The method cannot declare any ByRef parameters.

如果方法的return語句有類型為 TResult 的運算元,您可以為非同步方法的傳回類型指定 Task(Of TResult)You specify Task(Of TResult) for the return type of an async method if the Return statement of the method has an operand of type TResult. 如果方法完成時未傳回任何有意義的值,則使用 TaskYou use Task if no meaningful value is returned when the method is completed. 也就是說,呼叫方法會傳回 Task,但是當 Task 完成時,任何等候 AwaitTask 陳述式都不會產生結果值。That is, a call to the method returns a Task, but when the Task is completed, any Await statement that's awaiting the Task doesn’t produce a result value.

Async 副程式主要是用來定義需要 Sub 程序的事件處理常式。Async subroutines are used primarily to define event handlers where a Sub procedure is required. 非同步副程式的呼叫端無法等候它,而且無法攔截方法擲回的例外狀況。The caller of an async subroutine can't await it and can't catch exceptions that the method throws.

如需詳細資訊和範例,請參閱非同步方法的傳回型別For more information and examples, see Async Return Types.

範例Example

下列範例將示範非同步事件處理常式、非同步 Lambda 運算式及非同步方法。The following examples show an async event handler, an async lambda expression, and an async method. 如需使用這些元素的完整範例,請參閱逐步解說:使用 Async 和 Await 存取 WebFor a full example that uses these elements, see Walkthrough: Accessing the Web by Using Async and Await. 您可以從開發人員程式碼範例下載逐步解說程式碼。You can download the walkthrough code from Developer Code Samples.

' 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

請參閱See also