Note
L’accès à cette page nécessite une autorisation. Vous pouvez essayer de vous connecter ou de modifier les répertoires.
L’accès à cette page nécessite une autorisation. Vous pouvez essayer de changer de répertoire.
Vous pouvez configurer un bouton que vous pouvez utiliser pour annuler une application asynchrone si vous ne souhaitez pas attendre qu’elle se termine. En suivant les exemples de cette rubrique, vous pouvez ajouter un bouton d’annulation à une application qui télécharge le contenu d’un site web ou une liste de sites web.
Les exemples utilisent l’interface utilisateur qui Fine-Tuning votre application asynchrone (Visual Basic) décrit.
Remarque
Pour exécuter les exemples, vous devez disposer de Visual Studio 2012 ou version ultérieure et du .NET Framework 4.5 ou ultérieur installé sur votre ordinateur.
Annuler une tâche
Le premier exemple associe le bouton Annuler à une tâche de téléchargement unique. Si vous choisissez le bouton pendant le téléchargement du contenu de l’application, le téléchargement est annulé.
Téléchargement de l’exemple
Vous pouvez télécharger le projet WPF (Windows Presentation Foundation) complet à partir de l’exemple Async : ajuster votre application , puis suivre ces étapes.
Décompressez le fichier que vous avez téléchargé, puis démarrez Visual Studio.
Dans la barre de menus, choisissez Fichier, Ouvrir, Projet/Solution.
Dans la boîte de dialogue Ouvrir un projet , ouvrez le dossier contenant l’exemple de code que vous avez décompressé, puis ouvrez le fichier de solution (.sln) pour AsyncFineTuningVB.
Dans l’Explorateur de solutions, ouvrez le menu contextuel du projet CancelATask , puis choisissez Définir comme projet de démarrage.
Choisissez la clé F5 pour exécuter le projet.
Choisissez les touches Ctrl+F5 pour exécuter le projet sans le déboguer.
Si vous ne souhaitez pas télécharger le projet, vous pouvez consulter les fichiers MainWindow.xaml.vb à la fin de cette rubrique.
Construction de l'exemple
Les modifications suivantes ajoutent un bouton Annuler à une application qui télécharge un site web. Si vous ne souhaitez pas télécharger ou générer l’exemple, vous pouvez passer en revue le produit final dans la section « Exemples complets » à la fin de cette rubrique. Les astérisques marquent les modifications dans le code.
Pour générer l’exemple vous-même, suivez les instructions de la section « Téléchargement de l’exemple », mais choisissez StarterCode comme projet de démarrage au lieu de CancelATask.
Ajoutez ensuite les modifications suivantes au fichier MainWindow.xaml.vb de ce projet.
Déclarez une
CancellationTokenSourcevariable,ctsqui est dans l’étendue de toutes les méthodes qui y accèdent.Class MainWindow ' ***Declare a System.Threading.CancellationTokenSource. Dim cts As CancellationTokenSourceAjoutez le gestionnaire d’événements suivant pour le bouton Annuler . Le gestionnaire d’événements utilise la CancellationTokenSource.Cancel méthode pour notifier
ctsquand l’utilisateur demande l’annulation.' ***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 SubApportez les modifications suivantes dans le gestionnaire d’événements pour le bouton Démarrer.
startButton_ClickInstanciez le
CancellationTokenSource,cts.' ***Instantiate the CancellationTokenSource. cts = New CancellationTokenSource()Dans l’appel à
AccessTheWebAsync, qui télécharge le contenu d’un site web spécifié, envoyez la CancellationTokenSource.Token propriété d’unctsargument. LaTokenpropriété propage le message si l’annulation est demandée. Ajoutez un bloc catch qui affiche un message si l’utilisateur choisit d’annuler l’opération de téléchargement. Le code suivant montre les modifications.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
Dans
AccessTheWebAsync, utilisez la HttpClient.GetAsync(String, CancellationToken) surcharge de laGetAsyncméthode dans le HttpClient type pour télécharger le contenu d’un site web.ctPassez , le CancellationToken paramètre deAccessTheWebAsync, comme deuxième argument. Le jeton contient le message si l’utilisateur choisit le bouton Annuler .Le code suivant montre les modifications dans
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 FunctionSi vous n’annulez pas le programme, il produit la sortie suivante :
Ready to download. Length of the downloaded string: 158125.Si vous choisissez le bouton Annuler avant la fin du téléchargement du contenu, le programme produit la sortie suivante :
Ready to download. Download canceled.
Annuler une liste de tâches
Vous pouvez étendre l’exemple précédent pour annuler de nombreuses tâches en associant la même CancellationTokenSource instance à chaque tâche. Si vous choisissez le bouton Annuler , vous annulez toutes les tâches qui ne sont pas encore terminées.
Téléchargement de l’exemple
Vous pouvez télécharger le projet WPF (Windows Presentation Foundation) complet à partir de l’exemple Async : ajuster votre application , puis suivre ces étapes.
Décompressez le fichier que vous avez téléchargé, puis démarrez Visual Studio.
Dans la barre de menus, choisissez Fichier, Ouvrir, Projet/Solution.
Dans la boîte de dialogue Ouvrir un projet , ouvrez le dossier contenant l’exemple de code que vous avez décompressé, puis ouvrez le fichier de solution (.sln) pour AsyncFineTuningVB.
Dans l’Explorateur de solutions, ouvrez le menu contextuel du projet CancelAListOfTasks , puis choisissez Définir comme projet de démarrage.
Choisissez la clé F5 pour exécuter le projet.
Choisissez les touches Ctrl+F5 pour exécuter le projet sans le déboguer.
Si vous ne souhaitez pas télécharger le projet, vous pouvez consulter les fichiers MainWindow.xaml.vb à la fin de cette rubrique.
Construction de l'exemple
Pour étendre l’exemple vous-même, suivez les instructions de la section « Téléchargement de l’exemple », mais choisissez CancelATask comme projet de démarrage. Ajoutez les modifications suivantes à ce projet. Les astérisques marquent les modifications apportées au programme.
Ajoutez une méthode pour créer une liste d’adresses web.
' ***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 FunctionAppelez la méthode dans
AccessTheWebAsync.' ***Call SetUpURLList to make a list of web addresses. Dim urlList As List(Of String) = SetUpURLList()Ajoutez la boucle
AccessTheWebAsyncsuivante pour traiter chaque adresse web de la liste.' ***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 NextComme affiche les longueurs, la méthode n’a pas besoin de retourner quoi que
AccessTheWebAsyncce soit. Supprimez l’instruction return et modifiez le type de retour de la méthode à Task la place de Task<TResult>.Async Function AccessTheWebAsync(ct As CancellationToken) As TaskAppelez la méthode à partir d’une
startButton_Clickinstruction au lieu d’une expression.Await AccessTheWebAsync(cts.Token)Si vous n’annulez pas le programme, il produit la sortie suivante :
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.Si vous choisissez le bouton Annuler avant la fin des téléchargements, la sortie contient les longueurs des téléchargements terminés avant l’annulation.
Length of the downloaded string: 35939. Length of the downloaded string: 237682. Length of the downloaded string: 128607. Downloads canceled.
Exemples complets
Les sections suivantes contiennent le code de chacun des exemples précédents. Notez que vous devez ajouter une référence pour System.Net.Http.
Vous pouvez télécharger les projets à partir de l’exemple Async : ajuster votre application.
Annuler un exemple de tâche
Le code suivant est le fichier MainWindow.xaml.vb complet pour l’exemple qui annule une seule tâche.
' 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.
Annuler une liste de tâches - Exemple
Le code suivant est le fichier de MainWindow.xaml.vb complet pour l’exemple qui annule une liste de tâches.
' 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.