Async (Visual Basic)

Async 修飾子を変更するメソッドまたは ラムダ式 が非同期であることを示します。このようなメソッドは 非同期のメソッドと呼ばれます。

非同期のメソッドでは、呼び出し元のスレッドをブロックする場合には、実行に時間のかかる処理を行う便利な方法を提供します。非同期のメソッド呼び出し元は非同期のメソッドを待たずに作業を再開できます。

[!メモ]

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] の 1 種類の式またはステートメントが含まれます。メソッドは、予期したタスクが完了するまで最初の Awaitに達する、この時点で中断されるまで、同期的に実行されます。一方、コントロールがメソッドの呼び出し元に返します。メソッドが Await の式またはステートメントが含まれていない場合、メソッドは同期メソッドがように中断されず、実行しません。コンパイラの警告は Await が含まれていないすべての非同期のメソッドにその状態がエラーを示す場合があるので、警告します。詳細については、コンパイラ エラー"を参照してください。

Async のキーワードは予約されていないキーワードです。これは、メソッドまたはラムダ式を変更するときにキーワードです。それ以外の場合は、識別子として解釈されます。

戻り値の型

非同期のメソッドは [サブ] のプロシージャ、または Task または Task<TResult>の戻り値の型を持つ [関数] の手順です。メソッドは ByRef のパラメーターを宣言できません。

メソッドの [Return] のステートメントに TResult 型のオペランドが非同期メソッドの戻り値の型に Task(Of TResult) を指定します。メソッドが完了すると、意味のある値が返されない Task を使用します。つまり、メソッドの呼び出しは Taskを返しますが、Task が完了すると、Task を待機する Await のどのステートメントで結果の値を生成しません。

単一のサブルーチンに Sub の手順が必要なイベント ハンドラーを定義するために主に使用されます。async のサブルーチンの呼び出し元は、を待機し、メソッドがスローする例外をキャッチできません。

使用例を含む詳細については、「非同期の戻り値の型 (C# および Visual Basic)」を参照してください。

使用例

次の例では、非同期のイベント ハンドラー、非同期のラムダ式と非同期のメソッドを示します。これらの要素を使用する完全な例については、チュートリアル: 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)