Annuler une tâche ou une liste de tâches (C# et Visual Basic)

Vous pouvez configurer un bouton que vous pouvez utiliser pour annuler une application async si vous ne souhaitez pas l'attente se termine.En suivant les exemples de cette rubrique, vous pouvez ajouter un bouton annuler à une application qui télécharge le contenu d'un site Web ou une liste de sites Web.

Les exemples utilisent l'interface utilisateur que Réglage de votre application Async (C# et Visual Basic) décrit.

[!REMARQUE]

Pour exécuter les exemples, vous devez avoir installé Visual Studio 2012 Visual Studio express 2012 pour le bureau Windows, ou .NET Framework 4,5 sur votre ordinateur.

annuler une tâche (C#)

Le premier exemple associe le bouton Annuler à une tâche unique de téléchargement.Si vous cliquez sur le bouton lorsque l'application télécharge le contenu, le téléchargement est annulé.

JJ155759.collapse_all(fr-fr,VS.110).gifTélécharger l'exemple

Vous pouvez télécharger le projet complet de Windows Presentation Foundation (WPF) de Exemple Async : Affiner votre application et puis suivre ces étapes.

  1. Décompressez le fichier que vous avez téléchargé, puis démarrez ensuite Visual Studio 2012.

  2. Dans la barre de menus, sélectionnez Fichier, Ouvrir, Projet/Solution.

  3. Dans la boîte de dialogue Ouvrir un projet, ouvrez le dossier qui contient l'exemple de code que vous avez décompressé, puis ouvre le fichier solution (.sln) pour AsyncFineTuningCS ou AsyncFineTuningVB.

  4. Dans Explorateur de solutions, ouvrez le menu contextuel CancelAfterOneTask , puis choisissez Définir comme projet de démarrage.

  5. Choisissez la touche F5 pour exécuter le projet.

    Choisissez les clés Ctrl+F5 pour exécuter le projet sans le déboguer.

Si vous ne souhaitez pas télécharger le projet, vous pouvez examiner les fichiers de MainWindow.xaml.vb ou MainWindow.xaml.cs à la fin de cette rubrique.

JJ155759.collapse_all(fr-fr,VS.110).gifCréation 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 examiner le produit sur dans la section « exemples » à la fin de cette rubrique.Les astérisques marquent les modifications du fichier de code.

Pour générer l'exemple vous-même, pas - à - pas, suivez les instructions dans la section « exemple » téléchargement, mais choisissez StarterCode comme Projet de départ au lieu CancelATask.

Ajoutez ensuite les modifications suivantes au fichier de MainWindow.xaml.vb ou MainWindow.xaml.cs de ce projet.

  1. Déclarez une variable CancellationTokenSource , cts, qui est dans la portée de toutes les méthodes qui y accèdent.

    Class MainWindow
    
        ' ***Declare a System.Threading.CancellationTokenSource.
        Dim cts As CancellationTokenSource
    
    public partial class MainWindow : Window
    {
        // ***Declare a System.Threading.CancellationTokenSource.
        CancellationTokenSource cts;
    
  2. Ajoutez le gestionnaire d'événements du bouton Annuler.Le gestionnaire d'événements utilise la méthode CancellationTokenSource.Cancel pour informer cts lorsque l'utilisateur a demandé 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 Sub
    
    // ***Add an event handler for the Cancel button.
    private void cancelButton_Click(object sender, RoutedEventArgs e)
    {
        if (cts != null)
        {
            cts.Cancel();
        }
    }
    
  3. Effectuez les modifications suivantes dans le gestionnaire d'évènements du bouton Démarrer , startButton_Click.

    • Instanciez CancellationTokenSource, cts.

      ' ***Instantiate the CancellationTokenSource.
      cts = New CancellationTokenSource()
      
      // ***Instantiate the CancellationTokenSource.
      cts = new CancellationTokenSource();
      
    • Dans l'appel à AccessTheWebAsync, qui télécharge le contenu d'un site Web spécifié, envoyez la propriété CancellationTokenSource.Token de cts comme argument.La propriété Token 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 affiche les modifications.

      Try
          ' ***Send a token to carry the message if cancellation is requested.
          Dim contentLength As Integer = Await AccessTheWebAsync(cts.Token)
      
          resultsTextBox.Text &=
              String.Format(vbCrLf & "Length of the downloaded string: {0}." & vbCrLf, contentLength)
      
          ' *** 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
      
      try
      {
          // ***Send a token to carry the message if cancellation is requested.
          int contentLength = await AccessTheWebAsync(cts.Token);
          resultsTextBox.Text +=
              String.Format("\r\nLength of the downloaded string: {0}.\r\n", contentLength);
      }
      // *** If cancellation is requested, an OperationCanceledException results.
      catch (OperationCanceledException)
      {
          resultsTextBox.Text += "\r\nDownload canceled.\r\n";
      }
      catch (Exception)
      {
          resultsTextBox.Text += "\r\nDownload failed.\r\n";
      }
      
  4. Dans AccessTheWebAsync, utilisez la surcharge de HttpClient.GetAsync(String, CancellationToken) de la méthode GetAsync dans le type HttpClient pour télécharger le contenu d'un site Web.Passez ct, le paramètre CancellationToken de AccessTheWebAsync, comme deuxième argument.Le jeton transporte le message si l'utilisateur choisit le bouton Annuler .

    Le code suivant illustre les changements 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 &=
            String.Format(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/en-us/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
    
    // ***Provide a parameter for the CancellationToken.
    async Task<int> AccessTheWebAsync(CancellationToken ct)
    {
        HttpClient client = new HttpClient();
    
        resultsTextBox.Text +=
            String.Format("\r\nReady to download.\r\n");
    
        // You might need to slow things down to have a chance to cancel.
        await Task.Delay(250);
    
        // GetAsync returns a Task<HttpResponseMessage>. 
        // ***The ct argument carries the message if the Cancel button is chosen.
        HttpResponseMessage response = await client.GetAsync("https://msdn.microsoft.com/en-us/library/dd470362.aspx", ct);
    
        // Retrieve the website contents from the HttpResponseMessage.
        byte[] urlContents = await response.Content.ReadAsByteArrayAsync();
    
        // The result of the method is the length of the downloaded website.
        return urlContents.Length;
    }
    
  5. Si vous ne stoppez pas le programme, il produit la sortie suivante.

    Ready to download.
    Length of the downloaded string: 158125.
    

    Si vous choisissez le bouton Annuler avant que le programme finisse de télécharger le contenu, le programme produit la sortie suivante.

    Ready to download.
    Download canceled.
    

Annule une liste de tâches

Vous pouvez étendre l'exemple précédent pour annuler de nombreuses tâches en associant la même instance de CancellationTokenSource à chaque tâche.Si vous choisissez le bouton Annuler , vous annulez toutes les tâches qui ne sont pas encore terminées.

JJ155759.collapse_all(fr-fr,VS.110).gifTélécharger l'exemple

Vous pouvez télécharger le projet complet de Windows Presentation Foundation (WPF) de Exemple Async : Affiner votre application et puis suivre ces étapes.

  1. Décompressez le fichier que vous avez téléchargé, puis démarrez ensuite Visual Studio 2012.

  2. Dans la barre de menus, sélectionnez Fichier, Ouvrir, Projet/Solution.

  3. Dans la boîte de dialogue Ouvrir un projet, ouvrez le dossier qui contient l'exemple de code que vous avez décompressé, puis ouvre le fichier solution (.sln) pour AsyncFineTuningCS ou AsyncFineTuningVB.

  4. Dans l' Explorateur de solutions, ouvrez le menu contextuel CancelAfterOneTask , puis choisissez Définir comme projet de démarrage.

  5. Choisissez la touche F5 pour exécuter le projet.

    Choisissez les clés Ctrl+F5 pour exécuter le projet sans le déboguer.

Si vous ne souhaitez pas télécharger le projet, vous pouvez examiner les fichiers de MainWindow.xaml.vb ou MainWindow.xaml.cs à la fin de cette rubrique.

JJ155759.collapse_all(fr-fr,VS.110).gifCréation de l'exemple

Pour étendre l'exemple vous-même, pas - à - pas, suivez les instructions dans la section « exemple » téléchargement, mais choisissez CancelATask comme Projet de départ.Ajoutez les modifications suivantes à ce projet.Les astérisques marquent les modifications du programme.

  1. 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/en-us/library/hh290138.aspx",
                "https://msdn.microsoft.com/en-us/library/hh290140.aspx",
                "https://msdn.microsoft.com/en-us/library/dd470362.aspx",
                "https://msdn.microsoft.com/en-us/library/aa578028.aspx",
                "https://msdn.microsoft.com/en-us/library/ms404677.aspx",
                "https://msdn.microsoft.com/en-us/library/ff730837.aspx"
            }
        Return urls
    End Function
    
    // ***Add a method that creates a list of web addresses.
    private List<string> SetUpURLList()
    {
        List<string> urls = new List<string> 
        { 
            "https://msdn.microsoft.com",
            "https://msdn.microsoft.com/en-us/library/hh290138.aspx",
            "https://msdn.microsoft.com/en-us/library/hh290140.aspx",
            "https://msdn.microsoft.com/en-us/library/dd470362.aspx",
            "https://msdn.microsoft.com/en-us/library/aa578028.aspx",
            "https://msdn.microsoft.com/en-us/library/ms404677.aspx",
            "https://msdn.microsoft.com/en-us/library/ff730837.aspx"
        };
        return urls;
    }
    
  2. Appelez la méthode dans AccessTheWebAsync.

    ' ***Call SetUpURLList to make a list of web addresses.
    Dim urlList As List(Of String) = SetUpURLList()
    
    // ***Call SetUpURLList to make a list of web addresses.
    List<string> urlList = SetUpURLList();
    
  3. Ajoutez la boucle suivante dans AccessTheWebAsync pour traiter chaque adresse Web dans 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 &=
            String.Format(vbCrLf & "Length of the downloaded string: {0}." & vbCrLf, urlContents.Length)
    Next
    
    // ***Add a loop to process the list of web addresses.
    foreach (var url in urlList)
    {
        // GetAsync returns a Task<HttpResponseMessage>. 
        // Argument ct carries the message if the Cancel button is chosen. 
        // ***Note that the Cancel button can cancel all remaining downloads.
        HttpResponseMessage response = await client.GetAsync(url, ct);
    
        // Retrieve the website contents from the HttpResponseMessage.
        byte[] urlContents = await response.Content.ReadAsByteArrayAsync();
    
        resultsTextBox.Text +=
            String.Format("\r\nLength of the downloaded string: {0}.\r\n", urlContents.Length);
    }
    
  4. Étant donné que AccessTheWebAsync affiche les longueurs, la méthode n'a rien besoin de retourner.Supprimez l'instruction return, puis modifiez le type de retour de la méthode pour Task au lieu de Task<TResult>.

    Async Function AccessTheWebAsync(ct As CancellationToken) As Task
    
    async Task AccessTheWebAsync(CancellationToken ct)
    

    Appelez la méthode à partir de startButton_Click à l'aide d'une instruction au lieu d'une expression.

    Await AccessTheWebAsync(cts.Token)
    
    await AccessTheWebAsync(cts.Token);
    
  5. Si vous ne stoppez 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 que les téléchargements soient terminés, la sortie contient les longueurs des téléchargements qui se sont terminées 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 pour chacun des exemples précédents.Notez que vous devez ajouter une référence pour System.Net.Http.

Vous pouvez télécharger le projet depuis Exemple Async : Affiner votre application.

JJ155759.collapse_all(fr-fr,VS.110).gifAnnulez un exemple de tâche

Le code suivant est le fichier complet de MainWindow.xaml.vb ou MainWindow.xaml.cs pour l'exemple qui annule une tâche unique.

' 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 &=
                String.Format(vbCrLf & "Length of the downloaded string: {0}." & vbCrLf, contentLength)

            ' *** 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 &=
            String.Format(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/en-us/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.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

// Add a using directive and a reference for System.Net.Http.
using System.Net.Http;

// Add the following using directive for System.Threading.

using System.Threading;
namespace CancelATask
{
    public partial class MainWindow : Window
    {
        // ***Declare a System.Threading.CancellationTokenSource.
        CancellationTokenSource cts;

        public MainWindow()
        {
            InitializeComponent();
        }


        private async void startButton_Click(object sender, RoutedEventArgs e)
        {
            // ***Instantiate the CancellationTokenSource.
            cts = new CancellationTokenSource();

            resultsTextBox.Clear();

            try
            {
                // ***Send a token to carry the message if cancellation is requested.
                int contentLength = await AccessTheWebAsync(cts.Token);
                resultsTextBox.Text +=
                    String.Format("\r\nLength of the downloaded string: {0}.\r\n", contentLength);
            }
            // *** If cancellation is requested, an OperationCanceledException results.
            catch (OperationCanceledException)
            {
                resultsTextBox.Text += "\r\nDownload canceled.\r\n";
            }
            catch (Exception)
            {
                resultsTextBox.Text += "\r\nDownload failed.\r\n";
            }

            // ***Set the CancellationTokenSource to null when the download is complete.
            cts = null; 
        }


        // ***Add an event handler for the Cancel button.
        private void cancelButton_Click(object sender, RoutedEventArgs e)
        {
            if (cts != null)
            {
                cts.Cancel();
            }
        }


        // ***Provide a parameter for the CancellationToken.
        async Task<int> AccessTheWebAsync(CancellationToken ct)
        {
            HttpClient client = new HttpClient();

            resultsTextBox.Text +=
                String.Format("\r\nReady to download.\r\n");

            // You might need to slow things down to have a chance to cancel.
            await Task.Delay(250);

            // GetAsync returns a Task<HttpResponseMessage>. 
            // ***The ct argument carries the message if the Cancel button is chosen.
            HttpResponseMessage response = await client.GetAsync("https://msdn.microsoft.com/en-us/library/dd470362.aspx", ct);

            // Retrieve the website contents from the HttpResponseMessage.
            byte[] urlContents = await response.Content.ReadAsByteArrayAsync();

            // The result of the method is the length of the downloaded website.
            return urlContents.Length;
        }
    }

    // Output for a successful download:

    // Ready to download.

    // Length of the downloaded string: 158125.


    // Or, if you cancel:

    // Ready to download.

    // Download canceled.
}

JJ155759.collapse_all(fr-fr,VS.110).gifAnnulez une liste d'exemples de tâches

Le code suivant est le fichier complet de MainWindow.xaml.vb ou MainWindow.xaml.cs 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 &=
                String.Format(vbCrLf & "Length of the downloaded string: {0}." & vbCrLf, urlContents.Length)
        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/en-us/library/hh290138.aspx",
                "https://msdn.microsoft.com/en-us/library/hh290140.aspx",
                "https://msdn.microsoft.com/en-us/library/dd470362.aspx",
                "https://msdn.microsoft.com/en-us/library/aa578028.aspx",
                "https://msdn.microsoft.com/en-us/library/ms404677.aspx",
                "https://msdn.microsoft.com/en-us/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.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

// Add a using directive and a reference for System.Net.Http.
using System.Net.Http;

// Add the following using directive for System.Threading.
using System.Threading;

namespace CancelAListOfTasks
{
    public partial class MainWindow : Window
    {
        // Declare a System.Threading.CancellationTokenSource.
        CancellationTokenSource cts;

        public MainWindow()
        {
            InitializeComponent();
        }


        private async void startButton_Click(object sender, RoutedEventArgs e)
        {
            // Instantiate the CancellationTokenSource.
            cts = new CancellationTokenSource();

            resultsTextBox.Clear();

            try
            {
                await AccessTheWebAsync(cts.Token);
                // ***Small change in the display lines.
                resultsTextBox.Text += "\r\nDownloads complete.";
            }
            catch (OperationCanceledException)
            {
                resultsTextBox.Text += "\r\nDownloads canceled.";
            }
            catch (Exception)
            {
                resultsTextBox.Text += "\r\nDownloads failed.";
            }

            // Set the CancellationTokenSource to null when the download is complete.
            cts = null;
        }


        // Add an event handler for the Cancel button.
        private void cancelButton_Click(object sender, RoutedEventArgs e)
        {
            if (cts != null)
            {
                cts.Cancel();
            }
        }


        // Provide a parameter for the CancellationToken.
        // ***Change the return type to Task because the method has no return statement.
        async Task AccessTheWebAsync(CancellationToken ct)
        {
            // Declare an HttpClient object.
            HttpClient client = new HttpClient();

            // ***Call SetUpURLList to make a list of web addresses.
            List<string> urlList = SetUpURLList();

            // ***Add a loop to process the list of web addresses.
            foreach (var url in urlList)
            {
                // GetAsync returns a Task<HttpResponseMessage>. 
                // Argument ct carries the message if the Cancel button is chosen. 
                // ***Note that the Cancel button can cancel all remaining downloads.
                HttpResponseMessage response = await client.GetAsync(url, ct);

                // Retrieve the website contents from the HttpResponseMessage.
                byte[] urlContents = await response.Content.ReadAsByteArrayAsync();

                resultsTextBox.Text +=
                    String.Format("\r\nLength of the downloaded string: {0}.\r\n", urlContents.Length);
            }
        }


        // ***Add a method that creates a list of web addresses.
        private List<string> SetUpURLList()
        {
            List<string> urls = new List<string> 
            { 
                "https://msdn.microsoft.com",
                "https://msdn.microsoft.com/en-us/library/hh290138.aspx",
                "https://msdn.microsoft.com/en-us/library/hh290140.aspx",
                "https://msdn.microsoft.com/en-us/library/dd470362.aspx",
                "https://msdn.microsoft.com/en-us/library/aa578028.aspx",
                "https://msdn.microsoft.com/en-us/library/ms404677.aspx",
                "https://msdn.microsoft.com/en-us/library/ff730837.aspx"
            };
            return urls;
        }
    }

    // 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.
}

Voir aussi

Référence

CancellationTokenSource

CancellationToken

Concepts

Programmation asynchrone avec Async et Await (C# et Visual Basic)

Réglage de votre application Async (C# et Visual Basic)

Autres ressources

Exemple Async : Affiner votre application