Een asynchrone taak of een lijst met taken annuleren (Visual Basic)
U kunt een knop instellen die u kunt gebruiken om een asynchrone toepassing te annuleren als u niet wilt wachten totdat deze is voltooid. Door de voorbeelden in dit onderwerp te volgen, kunt u een annuleringsknop toevoegen aan een toepassing waarmee de inhoud van één website of een lijst met websites wordt gedownload.
In de voorbeelden wordt de gebruikersinterface gebruikt die uw asynchrone toepassing (Visual Basic) beschrijft.
Notitie
Als u de voorbeelden wilt uitvoeren, moet Visual Studio 2012 of hoger en .NET Framework 4.5 of hoger op uw computer zijn geïnstalleerd.
Een taak annuleren
In het eerste voorbeeld wordt de knop Annuleren gekoppeld aan één downloadtaak. Als u de knop kiest terwijl de toepassing inhoud downloadt, wordt het downloaden geannuleerd.
Het voorbeeld downloaden
U kunt het volledige WPF-project (Windows Presentation Foundation) downloaden uit Async Sample: Uw toepassing verfijnen en vervolgens deze stappen uitvoeren.
Decomprim het bestand dat u hebt gedownload en start Vervolgens Visual Studio.
Kies Bestand, Openen, Project/Oplossing in de menubalk.
Open in het dialoogvenster Project openen de map met de voorbeeldcode die u hebt gedecomprimeerd en open het oplossingsbestand (.sln) voor AsyncFineTuningVB.
Open in Solution Explorer het snelmenu voor het project CancelATask en kies Instellen als Opstartproject.
Kies de F5-sleutel om het project uit te voeren.
Kies de Ctrl+F5-toetsen om het project uit te voeren zonder fouten op te sporen.
Als u het project niet wilt downloaden, kunt u de MainWindow.xaml.vb bestanden aan het einde van dit onderwerp bekijken.
Het voorbeeld bouwen
Met de volgende wijzigingen wordt een knop Annuleren toegevoegd aan een toepassing die een website downloadt. Als u het voorbeeld niet wilt downloaden of bouwen, kunt u het eindproduct bekijken in de sectie Volledige voorbeelden aan het einde van dit onderwerp. Sterretjes markeren de wijzigingen in de code.
Als u het voorbeeld zelf wilt bouwen, volgt u stap voor stap de instructies in de sectie 'Het voorbeeld downloaden', maar kiest u StarterCode als opstartprojectin plaats van CancelATask.
Voeg vervolgens de volgende wijzigingen toe aan het MainWindow.xaml.vb-bestand van dat project.
Declareer een
CancellationTokenSource
variabele,cts
die binnen het bereik valt voor alle methoden die er toegang toe hebben.Class MainWindow ' ***Declare a System.Threading.CancellationTokenSource. Dim cts As CancellationTokenSource
Voeg de volgende gebeurtenis-handler toe voor de knop Annuleren . De gebeurtenis-handler gebruikt de methode om op de CancellationTokenSource.Cancel hoogte te stellen
cts
wanneer de gebruiker annulering aanvraagt.' ***Add an event handler for the Cancel button. Private Sub cancelButton_Click(sender As Object, e As RoutedEventArgs) If cts IsNot Nothing Then cts.Cancel() End If End Sub
Breng de volgende wijzigingen aan in de gebeurtenis-handler voor de knop Start.
startButton_Click
Instantieer de
CancellationTokenSource
,cts
.' ***Instantiate the CancellationTokenSource. cts = New CancellationTokenSource()
In de aanroep naar
AccessTheWebAsync
, waarmee de inhoud van een opgegeven website wordt gedownload, verzendt u de CancellationTokenSource.Token eigenschap vancts
als argument. DeToken
eigenschap stuurt het bericht door als annulering wordt aangevraagd. Voeg een catch-blok toe dat een bericht weergeeft als de gebruiker ervoor kiest om de downloadbewerking te annuleren. De volgende code toont de wijzigingen.Try ' ***Send a token to carry the message if cancellation is requested. Dim contentLength As Integer = Await AccessTheWebAsync(cts.Token) resultsTextBox.Text &= vbCrLf & $"Length of the downloaded string: {contentLength}." & vbCrLf ' *** If cancellation is requested, an OperationCanceledException results. Catch ex As OperationCanceledException resultsTextBox.Text &= vbCrLf & "Download canceled." & vbCrLf Catch ex As Exception resultsTextBox.Text &= vbCrLf & "Download failed." & vbCrLf End Try
Gebruik
AccessTheWebAsync
de HttpClient.GetAsync(String, CancellationToken) overbelasting van deGetAsync
methode in het HttpClient type om de inhoud van een website te downloaden. Geefct
, de CancellationToken parameter vanAccessTheWebAsync
, als het tweede argument. Het token bevat het bericht als de gebruiker de knop Annuleren kiest.De volgende code toont de wijzigingen in
AccessTheWebAsync
.' ***Provide a parameter for the CancellationToken. Async Function AccessTheWebAsync(ct As CancellationToken) As Task(Of Integer) Dim client As HttpClient = New HttpClient() resultsTextBox.Text &= vbCrLf & "Ready to download." & vbCrLf ' You might need to slow things down to have a chance to cancel. Await Task.Delay(250) ' GetAsync returns a Task(Of HttpResponseMessage). ' ***The ct argument carries the message if the Cancel button is chosen. Dim response As HttpResponseMessage = Await client.GetAsync("https://msdn.microsoft.com/library/dd470362.aspx", ct) ' Retrieve the website contents from the HttpResponseMessage. Dim urlContents As Byte() = Await response.Content.ReadAsByteArrayAsync() ' The result of the method is the length of the downloaded website. Return urlContents.Length End Function
Als u het programma niet annuleert, produceert het de volgende uitvoer:
Ready to download. Length of the downloaded string: 158125.
Als u de knop Annuleren kiest voordat het programma klaar is met het downloaden van de inhoud, produceert het programma de volgende uitvoer:
Ready to download. Download canceled.
Een lijst met taken annuleren
U kunt het vorige voorbeeld uitbreiden om veel taken te annuleren door hetzelfde CancellationTokenSource
exemplaar aan elke taak te koppelen. Als u de knop Annuleren kiest, annuleert u alle taken die nog niet zijn voltooid.
Het voorbeeld downloaden
U kunt het volledige WPF-project (Windows Presentation Foundation) downloaden uit Async Sample: Uw toepassing verfijnen en vervolgens deze stappen uitvoeren.
Decomprim het bestand dat u hebt gedownload en start Vervolgens Visual Studio.
Kies Bestand, Openen, Project/Oplossing in de menubalk.
Open in het dialoogvenster Project openen de map met de voorbeeldcode die u hebt gedecomprimeerd en open het oplossingsbestand (.sln) voor AsyncFineTuningVB.
Open in Solution Explorer het snelmenu voor het project CancelAListOfTasks en kies Instellen als Opstartproject.
Kies de F5-sleutel om het project uit te voeren.
Kies de Ctrl+F5-toetsen om het project uit te voeren zonder fouten op te sporen.
Als u het project niet wilt downloaden, kunt u de MainWindow.xaml.vb bestanden aan het einde van dit onderwerp bekijken.
Het voorbeeld bouwen
Als u het voorbeeld zelf wilt uitbreiden, volgt u stap voor stap de instructies in de sectie 'Het voorbeeld downloaden', maar kiest u CancelATask als het opstartproject. Voeg de volgende wijzigingen toe aan dat project. Sterretjes markeren de wijzigingen in het programma.
Voeg een methode toe om een lijst met webadressen te maken.
' ***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
Roep de methode aan in
AccessTheWebAsync
.' ***Call SetUpURLList to make a list of web addresses. Dim urlList As List(Of String) = SetUpURLList()
Voeg de volgende lus toe
AccessTheWebAsync
om elk webadres in de lijst te verwerken.' ***Add a loop to process the list of web addresses. 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
Omdat
AccessTheWebAsync
de lengten worden weergegeven, hoeft de methode niets te retourneren. Verwijder de retourinstructie en wijzig het retourtype van de methode Task in plaats van Task<TResult>.Async Function AccessTheWebAsync(ct As CancellationToken) As Task
Roep de methode aan
startButton_Click
met behulp van een instructie in plaats van een expressie.Await AccessTheWebAsync(cts.Token)
Als u het programma niet annuleert, produceert het de volgende uitvoer:
Length of the downloaded string: 35939. Length of the downloaded string: 237682. Length of the downloaded string: 128607. Length of the downloaded string: 158124. Length of the downloaded string: 204890. Length of the downloaded string: 175488. Length of the downloaded string: 145790. Downloads complete.
Als u de knop Annuleren kiest voordat de downloads zijn voltooid, bevat de uitvoer de lengten van de downloads die vóór de annulering zijn voltooid.
Length of the downloaded string: 35939. Length of the downloaded string: 237682. Length of the downloaded string: 128607. Downloads canceled.
Volledige voorbeelden
De volgende secties bevatten de code voor elk van de vorige voorbeelden. U moet een verwijzing toevoegen voor System.Net.Http.
U kunt de projecten downloaden uit Async Sample: Uw toepassing verfijnen.
Een taakvoorbeeld annuleren
De volgende code is het volledige MainWindow.xaml.vb bestand voor het voorbeeld dat één taak annuleert.
' 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
' ***Send a token to carry the message if cancellation is requested.
Dim contentLength As Integer = Await AccessTheWebAsync(cts.Token)
resultsTextBox.Text &=
vbCrLf & $"Length of the downloaded string: {contentLength}." & vbCrLf
' *** If cancellation is requested, an OperationCanceledException results.
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
' ***Add an event handler for the Cancel button.
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.
Async Function AccessTheWebAsync(ct As CancellationToken) As Task(Of Integer)
Dim client As HttpClient = New HttpClient()
resultsTextBox.Text &=
vbCrLf & "Ready to download." & vbCrLf
' You might need to slow things down to have a chance to cancel.
Await Task.Delay(250)
' GetAsync returns a Task(Of HttpResponseMessage).
' ***The ct argument carries the message if the Cancel button is chosen.
Dim response As HttpResponseMessage = Await client.GetAsync("https://msdn.microsoft.com/library/dd470362.aspx", ct)
' Retrieve the website contents from the HttpResponseMessage.
Dim urlContents As Byte() = Await response.Content.ReadAsByteArrayAsync()
' The result of the method is the length of the downloaded website.
Return urlContents.Length
End Function
End Class
' Output for a successful download:
' Ready to download.
' Length of the downloaded string: 158125.
' Or, if you cancel:
' Ready to download.
' Download canceled.
Een lijst met takenvoorbeeld annuleren
De volgende code is het volledige MainWindow.xaml.vb bestand voor het voorbeeld waarmee een lijst met taken wordt geannuleerd.
' 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
' ***AccessTheWebAsync returns a Task, not a Task(Of Integer).
Await AccessTheWebAsync(cts.Token)
' ***Small change in the display lines.
resultsTextBox.Text &= vbCrLf & "Downloads complete."
Catch ex As OperationCanceledException
resultsTextBox.Text &= vbCrLf & "Downloads canceled." & vbCrLf
Catch ex As Exception
resultsTextBox.Text &= vbCrLf & "Downloads failed." & vbCrLf
End Try
' Set the CancellationTokenSource to Nothing when the download is complete.
cts = Nothing
End Sub
' Add an event handler for the Cancel button.
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()
' ***Add a loop to process the list of web addresses.
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
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
' Output if you do not choose to cancel:
' Length of the downloaded string: 35939.
' Length of the downloaded string: 237682.
' Length of the downloaded string: 128607.
' Length of the downloaded string: 158124.
' Length of the downloaded string: 204890.
' Length of the downloaded string: 175488.
' Length of the downloaded string: 145790.
' Downloads complete.
' Sample output if you choose to cancel:
' Length of the downloaded string: 35939.
' Length of the downloaded string: 237682.
' Length of the downloaded string: 128607.
' Downloads canceled.