Sdílet prostřednictvím


Zrušení asynchronní úlohy nebo seznamu úloh (C# a Visual Basic)

Můžete nastavit tlačítko, které můžete použít ke zrušení asynchronní aplikace, pokud nechcete čekat na jeho dokončení.Podle příkladů v tomto tématu můžete přidat tlačítko pro zrušení do aplikace, která slouží k načtení obsahu jednoho webu nebo seznamu webů.

Příklady používají uživatelské rozhraní, které popisuje Vyladění aplikace s modifikátorem Async (C# a Visual Basic).

[!POZNÁMKA]

Chcete-li spustit příklady, musíte mít nainstalovanou aplikaci Visual Studio 2012, Visual Studio 2013, Visual Studio Express 2012 for Windows Desktop, Visual Studio Express 2013 for Windows nebo rozhraní .NET Framework 4.5 nebo 4.5.1 v počítači.

Zrušení úlohy

V prvním příkladu je k tlačítku Zrušit přidružen jeden úkol stahování.Pokud tlačítko použijete, když aplikace stahuje obsah, stahování bude zrušeno.

Stažení příkladu

Můžete si stáhnout kompletní projekt Windows Presentation Foundation (WPF) z části Asynchronní vzorek: Doladění aplikace a pak provést tyto kroky.

  1. Dekomprimujte soubor, který jste stáhli a poté spusťte Visual Studio.

  2. Na panelu nabídky vyberte možnosti Soubor, Otevřít, Projekt/řešení.

  3. V dialogovém okně Otevřít projekt otevřete složku, která obsahuje zdrojový k=od, který jste dekomprimovali, a pak otevřete soubor řešení (.sln) pro AsyncFineTuningCS nebo AsyncFineTuningVB.

  4. Průzkumníku řešení otevřete místní nabídku projektu CancelATask a vyberte položku Nastavit jako projekt po spuštění.

  5. Spusťte projekt tlačítkem F5.

    Vyberte klávesy Ctrl+F5 ke spuštění projektu bez ladění.

Pokud nechcete stáhnout projekt, můžete zkontrolovat soubory MainWindow.xaml.vb a MainWindow.xaml.cs na konci tohoto tématu.

Sestavení příkladu

Následující změny přidají tlačítko Zrušení pro aplikaci, která stahuje web.Pokud nechcete stahovat či sestavovat příklad, můžete si prohlédnout konečný produkt v části „Kompletní příklady“ na konci tohoto tématu.Hvězdičky označují změny v kódu.

Chcete-li vytvořit příklad sami krok za krokem, postupujte podle pokynů v oddíle "Stahování příkladu", ale zvolte StarterCode jako možnost Projekt po spuštění místo CancelATask.

Pak přidejte následující změny do souboru MainWindow.xaml.vb nebo MainWindow.xaml.cs tohoto projektu.

  1. Deklarujte proměnnou CancellationTokenSource, cts, která je v oboru pro všechny metody, které k ní přistupují.

    Class MainWindow
    
        ' ***Declare a System.Threading.CancellationTokenSource. 
        Dim cts As CancellationTokenSource
    
    public partial class MainWindow : Window
    {
        // ***Declare a System.Threading.CancellationTokenSource.
        CancellationTokenSource cts;
    
  2. Přidejte následující obslužnou rutinu události pro tlačítko Zrušit.Obslužná rutina události používá metodu CancellationTokenSource.Cancel pro oznámení cts, pokud uživatel požaduje zrušení.

    ' ***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. Proveďte následující změny v obslužné rutině události pro tlačítko StartstartButton_Click.

    • Vytvořte instance CancellationTokenSource, cts.

      ' ***Instantiate the CancellationTokenSource.
      cts = New CancellationTokenSource()
      
      // ***Instantiate the CancellationTokenSource.
      cts = new CancellationTokenSource();
      
    • Při volání metody AccessTheWebAsync, která stahuje obsah zadaného webu, odešlete vlastnost CancellationTokenSource.Token pro cts jako argument.Vlastnost Token šíří zprávy, pokud je požadováno zrušení.Přidáte blok catch, který zobrazí zprávu, pokud se uživatel rozhodne zrušit stahování.Následující kód ukazuje změny.

      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. V AccessTheWebAsync použijte přetížení HttpClient.GetAsync(String, CancellationToken) metody GetAsync v typu HttpClient ke stahování obsahu webu.Předá ct, parametr CancellationToken pro AccessTheWebAsync jako druhý argument.Token přenáší zprávy, vybere-li uživatel tlačítko Zrušit.

    Následující kód ukazuje změny v 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. Pokud nezrušíte program, vytvoří následující výstup.

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

    Pokud použijete tlačítko Storno dříve, než program dokončí stahování obsahu, program vygeneruje následující výstup.

    Ready to download.
    Download canceled.
    

Zrušení seznamu úloh

Můžete rozšířit předchozí příklad, a zrušit tak řadu úkolů propojením stejné instance CancellationTokenSource s jednotlivými úkoly.Pokud použijete tlačítko Storno, zrušíte všechny úlohy, které ještě nebyly dokončeny.

Stažení příkladu

Můžete si stáhnout kompletní projekt Windows Presentation Foundation (WPF) z části Asynchronní vzorek: Doladění aplikace a pak provést tyto kroky.

  1. Dekomprimujte soubor, který jste stáhli a poté spusťte Visual Studio 2012.

  2. Na panelu nabídky vyberte možnosti Soubor, Otevřít, Projekt/řešení.

  3. V dialogovém okně Otevřít projekt otevřete složku, která obsahuje zdrojový k=od, který jste dekomprimovali, a pak otevřete soubor řešení (.sln) pro AsyncFineTuningCS nebo AsyncFineTuningVB.

  4. Průzkumníku řešení otevřete místní nabídku projektu CancelAListOfTasks a vyberte položku Nastavit jako projekt po spuštění.

  5. Spusťte projekt tlačítkem F5.

    Vyberte klávesy Ctrl+F5 ke spuštění projektu bez ladění.

Pokud nechcete stáhnout projekt, můžete zkontrolovat soubory MainWindow.xaml.vb a MainWindow.xaml.cs na konci tohoto tématu.

Sestavení příkladu

Chcete-li rozšířit příklad sami krok za krokem, postupujte podle pokynů v oddíle "Stahování příkladu", ale zvolte CancelATask jako možnost Projekt po spuštění.Přidejte do tohoto projektu následující změny.Hvězdičky označují změny v programu.

  1. Přidejte metodu pro vytvoření seznamu webových adres.

    ' ***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. Volejte metodu v 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. Přidejte následující smyčku v AccessTheWebAsync pro zpracování každé webové adresy v seznamu.

    ' ***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. Protože AccessTheWebAsync zobrazí délky, metoda nemusí nic vrátit.Odeberte příkaz return a změňte návratový typ metody pro Task místo Task.

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

    Volejte metodu z startButton_Click pomocí příkazu namísto výrazu.

    Await AccessTheWebAsync(cts.Token)
    
    await AccessTheWebAsync(cts.Token);
    
  5. Pokud nezrušíte program, vytvoří následující výstup.

    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.
    

    Pokud použijete tlačítko Storno před dokončením stahování, obsahuje výstup rozsah stahování, který byl dokončen před zrušením.

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

Kompletní příklady

Následující části obsahují kód pro každý z předchozích příkladů.Všimněte si, že je nutné přidat odkaz pro System.Net.Http.

Projekty si můžete stáhnout na stránkách Asynchronní vzorek: Jemné ladění aplikace.

Příklad zrušení úlohy

Následující kód je celý soubor MainWindow.xaml.vb nebo MainWindow.xaml.cs pro příklad, který zruší jednu úlohu.

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

Příklad zrušení seznamu úloh

Následující kód je celý soubor MainWindow.xaml.vb nebo MainWindow.xaml.cs pro příklad, který zruší seznam úkolů.

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

Viz také

Referenční dokumentace

CancellationTokenSource

CancellationToken

Koncepty

Asynchronní programování pomocí modifikátoru Async a operátoru Await (C# a Visual Basic)

Vyladění aplikace s modifikátorem Async (C# a Visual Basic)

Další zdroje

Asynchronní vzorek: Jemné ladění aplikace