Task.WhenAnyメソッドをCancellationTokenと共に使用すると、1 つのタスクが完了したときに残りのすべてのタスクを取り消すことができます。
WhenAny
メソッドは、タスクのコレクションである引数を受け取ります。 このメソッドは、すべてのタスクを開始し、1 つのタスクを返します。 コレクション内のタスクが完了すると、1 つのタスクが完了します。
この例では、取り消しトークンを WhenAny
と組み合わせて使用して、最初のタスクを保持してタスクのコレクションから終了し、残りのタスクを取り消す方法を示します。 各タスクは、Web サイトの内容をダウンロードします。 この例では、完了する最初のダウンロードの内容の長さを表示し、他のダウンロードを取り消します。
注
この例を実行するには、Visual Studio 2012 以降と .NET Framework 4.5 以降がコンピューターにインストールされている必要があります。
サンプルをダウンロード
完全な Windows Presentation Foundation (WPF) プロジェクトは 、非同期サンプル: アプリケーションの微調整 からダウンロードし、次の手順に従います。
ダウンロードしたファイルを展開し、Visual Studio を起動します。
メニュー バーで、[ ファイル]、[ 開く]、[ プロジェクト/ソリューション] の順に選択します。
[ プロジェクトを開く ] ダイアログ ボックスで、展開したサンプル コードを保持するフォルダーを開き、AsyncFineTuningVB のソリューション (.sln) ファイルを開きます。
ソリューション エクスプローラーで、CancelAfterOneTask プロジェクトのショートカット メニューを開き、[スタートアップ プロジェクトとして設定] を選択します。
F5 キーを押してプロジェクトを実行します。
Ctrl キーを押しながら F5 キーを押して、プロジェクトをデバッグせずに実行します。
プログラムを複数回実行して、別のダウンロードが最初に完了することを確認します。
プロジェクトをダウンロードしない場合は、このトピックの最後にあるMainWindow.xaml.vb ファイルを確認できます。
例を構築する
このトピックの例では、「 非同期タスクの取り消し」または「タスクのリスト 」で開発したプロジェクトを追加して、タスクの一覧を取り消します。 この例では同じ UI を使用しますが、[ キャンセル ] ボタンは明示的には使用されません。
サンプルを自分でビルドするには、「サンプルのダウンロード」セクションの手順に従いますが、スタートアップ プロジェクトとして CancelAListOfTasks を選択します。 このトピックの変更をそのプロジェクトに追加します。
CancelAListOfTasks プロジェクトのMainWindow.xaml.vb ファイルで、各 Web サイトの処理手順を、AccessTheWebAsync
のループから次の非同期メソッドに移動することによって移行を開始します。
' ***Bundle the processing steps for a website into one async method.
Async Function ProcessURLAsync(url As String, client As HttpClient, ct As CancellationToken) As Task(Of Integer)
' GetAsync returns a Task(Of HttpResponseMessage).
Dim response As HttpResponseMessage = Await client.GetAsync(url, ct)
' Retrieve the website contents from the HttpResponseMessage.
Dim urlContents As Byte() = Await response.Content.ReadAsByteArrayAsync()
Return urlContents.Length
End Function
AccessTheWebAsync
では、この例ではクエリ、ToArray メソッド、および WhenAny
メソッドを使用して、タスクの配列を作成して開始します。 配列に WhenAny
を適用すると、待機すると最初のタスクに評価され、タスクの配列の完了に達する 1 つのタスクが返されます。
AccessTheWebAsync
で次の変更を行います。 アスタリスクは、コード ファイル内の変更をマークします。
ループをコメント アウトまたは削除します。
実行されると、一般的なタスクのコレクションを生成するクエリを作成します。
ProcessURLAsync
を呼び出すたびに、TResult
が整数であるTask<TResult>が返されます。' ***Create a query that, when executed, returns a collection of tasks. Dim downloadTasksQuery As IEnumerable(Of Task(Of Integer)) = From url In urlList Select ProcessURLAsync(url, client, ct)
ToArray
を呼び出してクエリを実行し、タスクを開始します。 次の手順でWhenAny
メソッドを適用すると、クエリが実行され、ToArray
を使用せずにタスクが開始されますが、他のメソッドでは実行されない場合があります。 最も安全な方法は、クエリの実行を明示的に強制することです。' ***Use ToArray to execute the query and start the download tasks. Dim downloadTasks As Task(Of Integer)() = downloadTasksQuery.ToArray()
タスクのコレクションに対して
WhenAny
を呼び出します。WhenAny
は、Task(Of Task(Of Integer))
またはTask<Task<int>>
を返します。 つまり、WhenAny
は、待機中に 1 つのTask(Of Integer)
またはTask<int>
に評価されるタスクを返します。 この 1 つのタスクは、コレクション内で最初に完了するタスクです。 最初に完了したタスクは、finishedTask
に割り当てられます。finishedTask
の型はTask<TResult>TResult
ProcessURLAsync
の戻り値の型であるため、整数です。' ***Call WhenAny and then await the result. The task that finishes ' first is assigned to finishedTask. Dim finishedTask As Task(Of Integer) = Await Task.WhenAny(downloadTasks)
この例では、最初に完了したタスクにのみ関心があります。 そのため、 CancellationTokenSource.Cancel を使用して残りのタスクを取り消します。
' ***Cancel the rest of the downloads. You just want the first one. cts.Cancel()
最後に、ダウンロードしたコンテンツの長さを取得するために
finishedTask
待つ。Dim length = Await finishedTask resultsTextBox.Text &= vbCrLf & $"Length of the downloaded website: {length}" & vbCrLf
プログラムを複数回実行して、別のダウンロードが最初に完了することを確認します。
コード例全体
次のコードは、この例の完全なMainWindow.xaml.vbまたはMainWindow.xaml.cs ファイルです。 アスタリスクは、この例で追加された要素を示します。
System.Net.Httpの参照を追加する必要があることに注意してください。
非同期サンプル: アプリケーションの微調整からプロジェクトをダウンロードできます。
' Add an Imports directive and a reference for System.Net.Http.
Imports System.Net.Http
' Add the following Imports directive for System.Threading.
Imports System.Threading
Class MainWindow
' Declare a System.Threading.CancellationTokenSource.
Dim cts As CancellationTokenSource
Private Async Sub startButton_Click(sender As Object, e As RoutedEventArgs)
' Instantiate the CancellationTokenSource.
cts = New CancellationTokenSource()
resultsTextBox.Clear()
Try
Await AccessTheWebAsync(cts.Token)
resultsTextBox.Text &= vbCrLf & "Download complete."
Catch ex As OperationCanceledException
resultsTextBox.Text &= vbCrLf & "Download canceled." & vbCrLf
Catch ex As Exception
resultsTextBox.Text &= vbCrLf & "Download failed." & vbCrLf
End Try
' Set the CancellationTokenSource to Nothing when the download is complete.
cts = Nothing
End Sub
' You can still include a Cancel button if you want to.
Private Sub cancelButton_Click(sender As Object, e As RoutedEventArgs)
If cts IsNot Nothing Then
cts.Cancel()
End If
End Sub
' Provide a parameter for the CancellationToken.
' Change the return type to Task because the method has no return statement.
Async Function AccessTheWebAsync(ct As CancellationToken) As Task
Dim client As HttpClient = New HttpClient()
' Call SetUpURLList to make a list of web addresses.
Dim urlList As List(Of String) = SetUpURLList()
'' Comment out or delete the loop.
''For Each url In urlList
'' ' GetAsync returns a Task(Of HttpResponseMessage).
'' ' Argument ct carries the message if the Cancel button is chosen.
'' ' Note that the Cancel button can cancel all remaining downloads.
'' Dim response As HttpResponseMessage = Await client.GetAsync(url, ct)
'' ' Retrieve the website contents from the HttpResponseMessage.
'' Dim urlContents As Byte() = Await response.Content.ReadAsByteArrayAsync()
'' resultsTextBox.Text &=
'' vbCrLf & $"Length of the downloaded string: {urlContents.Length}." & vbCrLf
''Next
' ***Create a query that, when executed, returns a collection of tasks.
Dim downloadTasksQuery As IEnumerable(Of Task(Of Integer)) =
From url In urlList Select ProcessURLAsync(url, client, ct)
' ***Use ToArray to execute the query and start the download tasks.
Dim downloadTasks As Task(Of Integer)() = downloadTasksQuery.ToArray()
' ***Call WhenAny and then await the result. The task that finishes
' first is assigned to finishedTask.
Dim finishedTask As Task(Of Integer) = Await Task.WhenAny(downloadTasks)
' ***Cancel the rest of the downloads. You just want the first one.
cts.Cancel()
' ***Await the first completed task and display the results
' Run the program several times to demonstrate that different
' websites can finish first.
Dim length = Await finishedTask
resultsTextBox.Text &= vbCrLf & $"Length of the downloaded website: {length}" & vbCrLf
End Function
' ***Bundle the processing steps for a website into one async method.
Async Function ProcessURLAsync(url As String, client As HttpClient, ct As CancellationToken) As Task(Of Integer)
' GetAsync returns a Task(Of HttpResponseMessage).
Dim response As HttpResponseMessage = Await client.GetAsync(url, ct)
' Retrieve the website contents from the HttpResponseMessage.
Dim urlContents As Byte() = Await response.Content.ReadAsByteArrayAsync()
Return urlContents.Length
End Function
' Add a method that creates a list of web addresses.
Private Function SetUpURLList() As List(Of String)
Dim urls = New List(Of String) From
{
"https://msdn.microsoft.com",
"https://msdn.microsoft.com/library/hh290138.aspx",
"https://msdn.microsoft.com/library/hh290140.aspx",
"https://msdn.microsoft.com/library/dd470362.aspx",
"https://msdn.microsoft.com/library/aa578028.aspx",
"https://msdn.microsoft.com/library/ms404677.aspx",
"https://msdn.microsoft.com/library/ff730837.aspx"
}
Return urls
End Function
End Class
' Sample output:
' Length of the downloaded website: 158856
' Download complete.
こちらも参照ください
.NET