非同期メソッドでは、タスクは作成時に開始されます。 Await 演算子は、タスクが完了するまで処理を続行できないメソッド内のポイントでタスクに適用されます。 多くの場合、次の例に示すように、タスクは作成されるとすぐに待たれます。
Dim result = Await someWebAccessMethodAsync(url)
ただし、タスクの完了に依存しない他の作業がプログラムに含まれている場合は、タスクの作成とタスクの待機を切り離すことができます。
' The following line creates and starts the task.
Dim myTask = someWebAccessMethodAsync(url)
' While the task is running, you can do other work that does not depend
' on the results of the task.
' . . . . .
' The application of Await suspends the rest of this method until the task is
' complete.
Dim result = Await myTask
タスクの開始と待機の間に、他のタスクを開始できます。 追加のタスクは暗黙的に並列で実行されますが、追加のスレッドは作成されません。
次のプログラムは、3 つの非同期 Web ダウンロードを開始し、呼び出された順序で待機します。 プログラムを実行するときに、タスクが作成されて待機されている順序でタスクが完了するとは限らないことに注意してください。 作成されると実行が開始され、メソッドが await 式に到達する前に 1 つ以上のタスクが終了する場合があります。
注
このプロジェクトを完了するには、Visual Studio 2012 以降と .NET Framework 4.5 以降がコンピューターにインストールされている必要があります。
複数のタスクを同時に開始する別の例については、「 方法: Task.WhenAll を使用して非同期チュートリアルを拡張する (Visual Basic)」を参照してください。
この例のコードは 、開発者コード サンプルからダウンロードできます。
プロジェクトを設定するには
WPF アプリケーションを設定するには、次の手順を実行します。 これらの手順の詳細な手順については、「 チュートリアル: Async と Await を使用した Web へのアクセス (Visual Basic)」を参照してください。
テキスト ボックスとボタンを含む WPF アプリケーションを作成します。 ボタン
startButton
に名前を付け、テキスト ボックスにresultsTextBox
名前を付けます。System.Net.Httpの参照を追加します。
MainWindow.xaml.vb ファイルに、
Imports
ステートメントをSystem.Net.Http
に追加します。
コードを追加するには
デザイン ウィンドウの MainWindow.xaml で、ボタンをダブルクリックして、MainWindow.xaml.vbに
startButton_Click
イベント ハンドラーを作成します。次のコードをコピーし、MainWindow.xaml.vbの
startButton_Click
の本文に貼り付けます。resultsTextBox.Clear() Await CreateMultipleTasksAsync() resultsTextBox.Text &= vbCrLf & "Control returned to button1_Click."
このコードは、アプリケーションを駆動する非同期メソッド
CreateMultipleTasksAsync
を呼び出します。プロジェクトに次のサポート メソッドを追加します。
ProcessURLAsync
では、 HttpClient メソッドを使用して、Web サイトの内容をバイト配列としてダウンロードします。 サポート メソッドProcessURLAsync
、配列の長さを表示して返します。DisplayResults
には、各 URL のバイト配列内のバイト数が表示されます。 この表示には、各タスクのダウンロードが完了した日時が表示されます。
次のメソッドをコピーし、MainWindow.xaml.vbの
startButton_Click
イベント ハンドラーの後に貼り付けます。Private Async Function ProcessURLAsync(url As String, client As HttpClient) As Task(Of Integer) Dim byteArray = Await client.GetByteArrayAsync(url) DisplayResults(url, byteArray) Return byteArray.Length End Function Private Sub DisplayResults(url As String, content As Byte()) ' Display the length of each website. The string format ' is designed to be used with a monospaced font, such as ' Lucida Console or Global Monospace. Dim bytes = content.Length ' Strip off the "https://". Dim displayURL = url.Replace("https://", "") resultsTextBox.Text &= String.Format(vbCrLf & "{0,-58} {1,8}", displayURL, bytes) End Sub
最後に、次の手順を実行するメソッド
CreateMultipleTasksAsync
を定義します。このメソッドは
HttpClient
オブジェクトを宣言します。このオブジェクトは、GetByteArrayAsync内のメソッドProcessURLAsync
にアクセスする必要があります。このメソッドは、 Task<TResult>型の 3 つのタスクを作成して開始します。ここで、
TResult
は整数です。 各タスクが完了すると、DisplayResults
タスクの URL とダウンロードしたコンテンツの長さが表示されます。 タスクは非同期的に実行されているため、結果が表示される順序が、宣言された順序と異なる場合があります。このメソッドは、各タスクの完了を待機します。 各
Await
オペレーターは、待機中のタスクが完了するまで、CreateMultipleTasksAsync
の実行を中断します。 また、オペレーターは、完了した各タスクからProcessURLAsync
する呼び出しから戻り値を取得します。タスクが完了し、整数値が取得されると、メソッドは Web サイトの長さを合計して結果を表示します。
次のメソッドをコピーし、ソリューションに貼り付けます。
Private Async Function CreateMultipleTasksAsync() As Task ' Declare an HttpClient object, and increase the buffer size. The ' default buffer size is 65,536. Dim client As HttpClient = New HttpClient() With {.MaxResponseContentBufferSize = 1000000} ' Create and start the tasks. As each task finishes, DisplayResults ' displays its length. Dim download1 As Task(Of Integer) = ProcessURLAsync("https://msdn.microsoft.com", client) Dim download2 As Task(Of Integer) = ProcessURLAsync("https://msdn.microsoft.com/library/hh156528(VS.110).aspx", client) Dim download3 As Task(Of Integer) = ProcessURLAsync("https://msdn.microsoft.com/library/67w7t67f.aspx", client) ' Await each task. Dim length1 As Integer = Await download1 Dim length2 As Integer = Await download2 Dim length3 As Integer = Await download3 Dim total As Integer = length1 + length2 + length3 ' Display the total count for all of the websites. resultsTextBox.Text &= String.Format(vbCrLf & vbCrLf & "Total bytes returned: {0}" & vbCrLf, total) End Function
F5 キーを押してプログラムを実行し、[ スタート ] ボタンを選択します。
プログラムを複数回実行して、3 つのタスクが常に同じ順序で終了するとは限らないことと、完了した順序が必ずしも作成されて待機されている順序ではないことを確認します。
例
次のコードには、完全な例が含まれています。
' Add the following Imports statements, and add a reference for System.Net.Http.
Imports System.Net.Http
Class MainWindow
Async Sub startButton_Click(sender As Object, e As RoutedEventArgs) Handles startButton.Click
resultsTextBox.Clear()
Await CreateMultipleTasksAsync()
resultsTextBox.Text &= vbCrLf & "Control returned to button1_Click."
End Sub
Private Async Function CreateMultipleTasksAsync() As Task
' Declare an HttpClient object, and increase the buffer size. The
' default buffer size is 65,536.
Dim client As HttpClient =
New HttpClient() With {.MaxResponseContentBufferSize = 1000000}
' Create and start the tasks. As each task finishes, DisplayResults
' displays its length.
Dim download1 As Task(Of Integer) =
ProcessURLAsync("https://msdn.microsoft.com", client)
Dim download2 As Task(Of Integer) =
ProcessURLAsync("https://msdn.microsoft.com/library/hh156528(VS.110).aspx", client)
Dim download3 As Task(Of Integer) =
ProcessURLAsync("https://msdn.microsoft.com/library/67w7t67f.aspx", client)
' Await each task.
Dim length1 As Integer = Await download1
Dim length2 As Integer = Await download2
Dim length3 As Integer = Await download3
Dim total As Integer = length1 + length2 + length3
' Display the total count for all of the websites.
resultsTextBox.Text &= String.Format(vbCrLf & vbCrLf &
"Total bytes returned: {0}" & vbCrLf, total)
End Function
Private Async Function ProcessURLAsync(url As String, client As HttpClient) As Task(Of Integer)
Dim byteArray = Await client.GetByteArrayAsync(url)
DisplayResults(url, byteArray)
Return byteArray.Length
End Function
Private Sub DisplayResults(url As String, content As Byte())
' Display the length of each website. The string format
' is designed to be used with a monospaced font, such as
' Lucida Console or Global Monospace.
Dim bytes = content.Length
' Strip off the "https://".
Dim displayURL = url.Replace("https://", "")
resultsTextBox.Text &= String.Format(vbCrLf & "{0,-58} {1,8}", displayURL, bytes)
End Sub
End Class
こちらも参照ください
.NET