Cancelar uma tarefa assíncrona ou uma lista de tarefas (C# e Visual Basic)

Você pode configurar um botão para cancelar um aplicativo assíncrono se você não desejar esperar a conclusão. Ao seguir os exemplos neste tópico, você pode adicionar um botão de cancelar a um aplicativo que baixa o conteúdo de um site ou de uma lista de sites.

Os exemplos usam a interface do usuário que Ajustando seu aplicativo Async (C# e Visual Basic) descreve.

Dica

Para executar os exemplos, você deve ter o Visual Studio 2012, Visual Studio 2013, Visual Studio Express 2012 para Windows Desktop, Visual Studio Express 2013 para Windows, ou o .NET Framework 4.5 ou 4.5.1 instalado em seu computador.

Cancelar uma tarefa

O primeiro exemplo associa o botão Cancelar com uma única tarefa de download. Se você escolher o botão enquanto o aplicativo estiver baixando conteúdo, o download será cancelado.

Baixando o Exemplo

Você pode baixar projeto completo do Windows Presentation Foundation (WPF) de Exemplo de Async: Ajustando seu aplicativo.

  1. Descompacte o arquivo que você baixou e inicie o Visual Studio.

  2. Na barra de menu, escolha Arquivo, Abrir, Projeto/solução.

  3. Na caixa de diálogo Abrir Projeto , abra a pasta que contém o código de exemplo que você descompactou, e abra o arquivo de solução (.sln) para AsyncFineTuningCS ou AsyncFineTuningVB.

  4. Em Gerenciador de Soluções, abra o menu de atalho para o projeto CancelATask e escolha Definir como Projeto de Inicialização.

  5. Escolha a tecla F5 para executar o projeto.

    Escolha as chaves Ctrl+F5 para executar o projeto sem depurá-las.

Se você não quiser baixar o projeto, você pode examinar os arquivos de MainWindow.xaml.vb e de MainWindow.xaml.cs no final deste tópico.

Compilando o Exemplo

As seguintes alterações adicionam um botão Cancelar a um aplicativo que baixa um site. Se você não deseja baixar ou compilar o exemplo, poderá examinar o produto final na seção “Exemplos Completos" no final deste tópico. Os asteriscos marcam as alterações no código.

Para criar o exemplo você mesmo, passo a passo, siga as instruções na seção "Baixando o exemplo", mas selecione StarterCode como Projeto de inicialização em vez de CancelATask.

Adicione as seguintes alterações ao arquivo MainWindow.xaml.vb ou MainWindow.xaml.cs do projeto.

  1. Declarar uma variável CancellationTokenSource, cts, no escopo para todos os métodos que o acessam.

    Class MainWindow
    
        ' ***Declare a System.Threading.CancellationTokenSource. 
        Dim cts As CancellationTokenSource
    
    public partial class MainWindow : Window
    {
        // ***Declare a System.Threading.CancellationTokenSource.
        CancellationTokenSource cts;
    
  2. Adicione o seguinte manipulador de eventos para o botão Cancelar. O manipulador de eventos usa o método de CancellationTokenSource.Cancel para notificar cts quando o usuário solicita o cancelamento.

    ' ***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. Verifique as alterações a seguir no manipulador de eventos para o botão Iniciar, startButton_Click.

    • Instancie o CancellationTokenSource, cts.

      ' ***Instantiate the CancellationTokenSource.
      cts = New CancellationTokenSource()
      
      // ***Instantiate the CancellationTokenSource.
      cts = new CancellationTokenSource();
      
    • Na chamada a AccessTheWebAsync, que baixa o conteúdo de um site especificado, envie a propriedade CancellationTokenSource.Token de cts como um argumento. A propriedade Token propaga a mensagem se o cancelamento for solicitado. Adicione um bloco catch que exibe uma mensagem se o usuário decidir cancelar a operação de download. O código a seguir mostra as alterações.

      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. Em AccessTheWebAsync, use a sobrecarga HttpClient.GetAsync(String, CancellationToken) do método GetAsync no tipo HttpClient para baixar o conteúdo de um site. Passe ct, o parâmetro de CancellationToken de AccessTheWebAsync, como o segundo argumento. O token leva a mensagem se o usuário clicar no botão Cancelar.

    O código a seguir mostra as alterações em 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. Se você não cancelar o programa, ele produzirá a saída a seguir.

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

    Se você escolher o botão Cancelar antes que o programa termine o download do conteúdo, o programa produzirá a saída a seguir.

    Ready to download.
    Download canceled.
    

Cancela uma lista de tarefas

Você pode estender o exemplo anterior para cancelar muitas tarefas associando a mesma instância de CancellationTokenSource com cada tarefa. Se você escolher o botão Cancelar, cancelará todas as tarefas que ainda não estejam concluídas.

Baixando o Exemplo

Você pode baixar projeto completo do Windows Presentation Foundation (WPF) de Exemplo de Async: Ajustando seu aplicativo.

  1. Descompacte o arquivo que você baixou e inicie o Visual Studio 2012.

  2. Na barra de menu, escolha Arquivo, Abrir, Projeto/solução.

  3. Na caixa de diálogo Abrir Projeto , abra a pasta que contém o código de exemplo que você descompactou, e abra o arquivo de solução (.sln) para AsyncFineTuningCS ou AsyncFineTuningVB.

  4. Em Gerenciador de Soluções, abra o menu de atalho para o projeto CancelAListOfTasks e escolha Definir como Projeto de Inicialização.

  5. Escolha a tecla F5 para executar o projeto.

    Escolha as chaves Ctrl+F5 para executar o projeto sem depurá-las.

Se você não quiser baixar o projeto, você pode examinar os arquivos de MainWindow.xaml.vb e de MainWindow.xaml.cs no final deste tópico.

Compilando o Exemplo

Para estender o exemplo você mesmo, passo a passo, siga as instruções na seção "Baixando o exemplo", mas selecione Cancelar uma tarefa como Projeto de inicialização. Adicione as seguintes alterações ao projeto. Os asteriscos marcam as alterações no programa.

  1. Adicione um método para criar uma lista de endereços 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. Chame o método em 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. Adicione o seguinte loop em AccessTheWebAsync para processar cada endereço Web na lista.

    ' ***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. Como AccessTheWebAsync exibe os comprimentos, o método não precisa retornar nada. Remova a declaração de retorno e o tipo de retorno do método a Task em vez de Task.

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

    Chame o método de startButton_Click usando uma instrução em vez de uma expressão.

    Await AccessTheWebAsync(cts.Token)
    
    await AccessTheWebAsync(cts.Token);
    
  5. Se você não cancelar o programa, ele produzirá a saída a seguir.

    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.
    

    Se você escolher o botão Cancelar antes da conclusão dos downloads, a saída conterá os comprimentos dos downloads concluídos antes do cancelamento.

    Length of the downloaded string: 35939.
    
    Length of the downloaded string: 237682.
    
    Length of the downloaded string: 128607.
    
    Downloads canceled.
    

Exemplos completos

As seções a seguir contêm o código para cada um dos exemplos anteriores. Observe que você deve adicionar uma referência para System.Net.Http.

Você pode baixar projetos de Exemplo de Async: Ajustando seu aplicativo.

Cancelar um exemplo de tarefa

O código a seguir é o arquivo completo de MainWindow.xaml.vb ou de MainWindow.xaml.cs para um exemplo que cancela uma tarefa única.

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

Cancelar uma lista de exemplos de tarefa

O código a seguir é o arquivo completo de MainWindow.xaml.vb ou de MainWindow.xaml.cs para um exemplo que cancela uma lista de tarefas.

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

Consulte também

Referência

CancellationTokenSource

CancellationToken

Conceitos

Programação assíncrona com Async e Await (C# e Visual Basic)

Ajustando seu aplicativo Async (C# e Visual Basic)

Outros recursos

Exemplo de Async: Ajustando o aplicativo