Cancelar una tarea asincrónica o una lista de tareas (C# y Visual Basic)

Es posible establecer un botón que podrá usar para cancelar una aplicación asincrónica si no desea esperar a que finalice. Siguiendo los ejemplos de este tema, se puede agregar un botón de cancelación a una aplicación que descargue el contenido de un sitio web o de múltiples sitios web.

Los ejemplos utilizan la interfaz de usuario que Ajustar una aplicación asincrónica (C# y Visual Basic) describe.

Nota

Para ejecutar los ejemplos, debe tener Visual Studio 2012, Visual Studio 2013, Visual Studio Express 2012 para escritorio de Windows, Visual Studio Express 2013 para Windows, o .NET Framework 4.5 o 4.5.1 instalado en su equipo.

Cancelar una tarea

El primer ejemplo asocia el botón Cancelar a una única tarea de descarga. Si se elige el botón mientras la aplicación está descargando el contenido, la descarga se cancela.

Descargar el ejemplo

Puede descargar el proyecto completado de Windows Presentation Foundation (WPF) en Ejemplo Async: Ajuste de la aplicación y seguir estos pasos.

  1. Descomprima el archivo que ha descargado y, a continuación, inicie Visual Studio.

  2. En la barra de menú, elija Archivo, Abrir, Proyecto/Solución.

  3. En el cuadro Abrir proyecto, abra la carpeta que contiene código de ejemplo que descomprimió y, a continuación, abra el archivo de solución (.sln) para AsyncFineTuningCS o AsyncFineTuningVB.

  4. En el Explorador de soluciones, abra el acceso directo del proyecto CancelATask y, a continuación, elija Establecer como proyecto de inicio.

  5. Elija la tecla F5 para ejecutar el proyecto.

    Elija las teclas CTRL+F5 para ejecutar el proyecto sin depurarlo.

Si no desea descargar el proyecto, puede revisar los archivos completos de MainWindow.xaml.vb y de MainWindow.xaml.cs al final de este tema.

Compilar el ejemplo

Los cambios siguientes agregan un botón Cancelar a una aplicación que descarga un sitio web. Si no desea descargar o compilar el ejemplo, puede revisar el producto final en la sección "Ejemplos completos" al final de este tema. Los asteriscos marcan los cambios en el código.

Para compilar el ejemplo usted mismo, paso a paso, siga las instrucciones de la sección “Descargar el ejemplo” pero elija StarterCode como el Proyecto de inicio en lugar de CancelATask.

A continuación, agregue los cambios siguientes al archivo MainWindow.xaml.vb o MainWindow.xaml.cs de ese proyecto.

  1. Declare una variable CancellationTokenSource, cts, que está en el ámbito de todos los métodos que tengan acceso.

    Class MainWindow
    
        ' ***Declare a System.Threading.CancellationTokenSource. 
        Dim cts As CancellationTokenSource
    
    public partial class MainWindow : Window
    {
        // ***Declare a System.Threading.CancellationTokenSource.
        CancellationTokenSource cts;
    
  2. Agregue el siguiente controlador de eventos para el botón Cancelar. El controlador de eventos utiliza el método CancellationTokenSource.Cancel para notificar cts cuando el usuario solicita la cancelación.

    ' ***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. Realice los cambios siguientes en el controlador de eventos para el botón Iniciar, startButton_Click.

    • Cree la instancia CancellationTokenSource, cts.

      ' ***Instantiate the CancellationTokenSource.
      cts = New CancellationTokenSource()
      
      // ***Instantiate the CancellationTokenSource.
      cts = new CancellationTokenSource();
      
    • En la llamada a AccessTheWebAsync, que descarga el contenido de un sitio web especificado, envíe la propiedad CancellationTokenSource.Token de cts como argumento. La propiedad Token propaga el mensaje si se solicita la cancelación. Agregue un bloque catch que muestre un mensaje si el usuario decide cancelar la operación de descarga. El código siguiente muestra los cambios.

      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. En AccessTheWebAsync, utilice la sobrecarga de HttpClient.GetAsync(String, CancellationToken) del método de GetAsync en el tipo HttpClient para descargar el contenido de un sitio web. Pase ct, el parámetro CancellationToken de AccessTheWebAsync, como segundo argumento. El token lleva el mensaje si el usuario elige el botón Cancelar.

    El código siguiente muestra los cambios en 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 no cancela el programa, se genera el siguiente resultado.

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

    Si se elige el botón Cancelar antes de que el programa termine de descargar el contenido, el programa produce el siguiente resultado.

    Ready to download.
    Download canceled.
    

Cancelar una lista de tareas

Se puede ampliar el ejemplo anterior para cancelar muchas tareas asociando la misma instancia de CancellationTokenSource a cada tarea. Si se elige el botón Cancelar, se cancelan todas las tareas que aún no se han completado.

Descargar el ejemplo

Puede descargar el proyecto completado de Windows Presentation Foundation (WPF) en Ejemplo Async: Ajuste de la aplicación y seguir estos pasos.

  1. Descomprima el archivo que ha descargado y, a continuación, inicie Visual Studio 2012.

  2. En la barra de menú, elija Archivo, Abrir, Proyecto/Solución.

  3. En el cuadro Abrir proyecto, abra la carpeta que contiene código de ejemplo que descomprimió y, a continuación, abra el archivo de solución (.sln) para AsyncFineTuningCS o AsyncFineTuningVB.

  4. En el Explorador de soluciones, abra el acceso directo del proyecto CancelAListOfTasks y, a continuación, elija Establecer como proyecto de inicio.

  5. Elija la tecla F5 para ejecutar el proyecto.

    Elija las teclas CTRL+F5 para ejecutar el proyecto sin depurarlo.

Si no desea descargar el proyecto, puede revisar los archivos completos de MainWindow.xaml.vb y de MainWindow.xaml.cs al final de este tema.

Compilar el ejemplo

Para ampliar el ejemplo usted mismo, paso a paso, siga las instrucciones de la sección “Descargar el ejemplo” pero elija CancelATask como el Proyecto de inicio. Agregue los siguientes cambios a dicho proyecto. Los asteriscos marcan los cambios en el programa.

  1. Agregue un método para crear una lista de direcciones 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. Llame al método en 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. Agregue el bucle siguiente en AccessTheWebAsync para procesar cada dirección web en la 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. Dado que AccessTheWebAsync muestra las longitudes, el método no necesita devolver nada. Elimine la instrucción return y cambie el tipo de valor devuelto del método a Task en lugar de Task.

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

    Llame al método desde startButton_Click mediante un fragmento en lugar de una expresión.

    Await AccessTheWebAsync(cts.Token)
    
    await AccessTheWebAsync(cts.Token);
    
  5. Si no cancela el programa, se genera el siguiente resultado.

    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 elige el botón Cancelar antes de que se completen las descargas, la salida contiene las longitudes de descargas que se rellenan antes de la cancelación.

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

Ejemplos completos

Las secciones siguientes contienen el código para cada uno de los ejemplos anteriores. Observe que debe agregar una referencia para System.Net.Http.

Puede descargar los proyectos desde Ejemplo Async: Ajuste de la aplicación.

Cancelar un ejemplo de tarea

El código siguiente es el archivo completo de MainWindow.xaml.vb o de MainWindow.xaml.cs para el ejemplo que cancela una única tarea.

' 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 una lista de ejemplos de tareas

El código siguiente es el archivo completo de MainWindow.xaml.vb o de MainWindow.xaml.cs para el ejemplo que cancela una lista de tareas.

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

Vea también

Referencia

CancellationTokenSource

CancellationToken

Conceptos

Programación asincrónica con Async y Await (C# y Visual Basic)

Ajustar una aplicación asincrónica (C# y Visual Basic)

Otros recursos

Ejemplo Async: Ajuste de la aplicación (C# y Visual Basic)