Anulowanie zadania asynchronicznego lub listy zadań (Visual Basic)

Możesz skonfigurować przycisk, którego można użyć do anulowania aplikacji asynchronicznych, jeśli nie chcesz czekać na zakończenie. Postępując zgodnie z przykładami w tym temacie, możesz dodać przycisk anulowania do aplikacji, która pobiera zawartość jednej witryny internetowej lub listy witryn internetowych.

W przykładach użyto interfejsu użytkownika, który opisuje dostosowywanie aplikacji asynchronicznych (Visual Basic).

Uwaga

Aby uruchomić przykłady, na komputerze musi być zainstalowany program Visual Studio 2012 lub nowszy oraz program .NET Framework 4.5 lub nowszy.

Anulowanie zadania

Pierwszy przykład kojarzy przycisk Anuluj z pojedynczym zadaniem pobierania. Jeśli wybierzesz przycisk podczas pobierania zawartości przez aplikację, pobieranie zostanie anulowane.

Pobieranie przykładu

Pełny projekt programu Windows Presentation Foundation (WPF) można pobrać z przykładu Async: Dostosowywanie aplikacji , a następnie wykonaj następujące kroki.

  1. Zdekompresuj pobrany plik, a następnie uruchom program Visual Studio.

  2. Na pasku menu wybierz pozycję Plik, Otwórz, Projekt/Rozwiązanie.

  3. W oknie dialogowym Otwieranie projektu otwórz folder zawierający zdekompresowany przykładowy kod, a następnie otwórz plik rozwiązania (.sln) dla pliku AsyncFineTuningVB.

  4. W Eksplorator rozwiązań otwórz menu skrótów dla projektu CancelATask, a następnie wybierz pozycję Ustaw jako projekt startowy.

  5. Wybierz klucz F5, aby uruchomić projekt.

    Wybierz klawisze Ctrl+F5, aby uruchomić projekt bez debugowania.

Jeśli nie chcesz pobierać projektu, możesz przejrzeć pliki MainWindow.xaml.vb na końcu tego tematu.

Kompilowanie przykładu

Poniższe zmiany dodają przycisk Anuluj do aplikacji, która pobiera witrynę internetową. Jeśli nie chcesz pobrać ani skompilować przykładu, możesz przejrzeć końcowy produkt w sekcji "Kompletne przykłady" na końcu tego tematu. Gwiazdki oznaczają zmiany w kodzie.

Aby utworzyć przykład samodzielnie, wykonaj kroki krok po kroku, postępuj zgodnie z instrukcjami w sekcji "Pobieranie przykładu", ale wybierz pozycję StarterCode jako projekt startowy zamiast CancelATask.

Następnie dodaj następujące zmiany do pliku MainWindow.xaml.vb tego projektu.

  1. Zadeklaruj zmienną CancellationTokenSource , ctsktóra jest w zakresie dla wszystkich metod, które uzyskują do niej dostęp.

    Class MainWindow
    
        ' ***Declare a System.Threading.CancellationTokenSource.
        Dim cts As CancellationTokenSource
    
  2. Dodaj następującą procedurę obsługi zdarzeń dla przycisku Anuluj . Procedura obsługi zdarzeń używa CancellationTokenSource.Cancel metody do powiadamiania cts o żądaniu anulowania przez użytkownika.

    ' ***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
    
  3. Wprowadź następujące zmiany w procedurze obsługi zdarzeń dla przycisku Uruchom. startButton_Click

    • Utwórz wystąpienie elementu CancellationTokenSource, cts.

      ' ***Instantiate the CancellationTokenSource.
      cts = New CancellationTokenSource()
      
    • W wywołaniu metody AccessTheWebAsync, która pobiera zawartość określonej witryny internetowej, wyślij CancellationTokenSource.Token właściwość jako cts argument. Właściwość Token propaguje komunikat, jeśli zażądano anulowania. Dodaj blok catch wyświetlający komunikat, jeśli użytkownik zdecyduje się anulować operację pobierania. Poniższy kod przedstawia zmiany.

      Try
          ' ***Send a token to carry the message if cancellation is requested.
          Dim contentLength As Integer = Await AccessTheWebAsync(cts.Token)
      
          resultsTextBox.Text &=
              vbCrLf & $"Length of the downloaded string: {contentLength}." & vbCrLf
      
          ' *** If cancellation is requested, an OperationCanceledException results.
      Catch ex As OperationCanceledException
          resultsTextBox.Text &= vbCrLf & "Download canceled." & vbCrLf
      
      Catch ex As Exception
          resultsTextBox.Text &= vbCrLf & "Download failed." & vbCrLf
      End Try
      
  4. W AccessTheWebAsyncpliku użyj HttpClient.GetAsync(String, CancellationToken) przeciążenia GetAsync metody w typie HttpClient , aby pobrać zawartość witryny internetowej. Przekaż ctparametr AccessTheWebAsync, CancellationToken jako drugi argument. Token zawiera komunikat, jeśli użytkownik wybierze przycisk Anuluj .

    Poniższy kod przedstawia zmiany w pliku AccessTheWebAsync.

    ' ***Provide a parameter for the CancellationToken.
    Async Function AccessTheWebAsync(ct As CancellationToken) As Task(Of Integer)
    
        Dim client As HttpClient = New HttpClient()
    
        resultsTextBox.Text &= vbCrLf & "Ready to download." & vbCrLf
    
        ' You might need to slow things down to have a chance to cancel.
        Await Task.Delay(250)
    
        ' GetAsync returns a Task(Of HttpResponseMessage).
        ' ***The ct argument carries the message if the Cancel button is chosen.
        Dim response As HttpResponseMessage = Await client.GetAsync("https://msdn.microsoft.com/library/dd470362.aspx", ct)
    
        ' Retrieve the website contents from the HttpResponseMessage.
        Dim urlContents As Byte() = Await response.Content.ReadAsByteArrayAsync()
    
        ' The result of the method is the length of the downloaded website.
        Return urlContents.Length
    End Function
    
  5. Jeśli program nie zostanie anulowany, spowoduje to wygenerowanie następujących danych wyjściowych:

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

    Jeśli wybierzesz przycisk Anuluj przed zakończeniem pobierania zawartości przez program, program generuje następujące dane wyjściowe:

    Ready to download.
    Download canceled.
    

Anulowanie listy zadań

Poprzedni przykład można rozszerzyć, aby anulować wiele zadań, kojarząc to samo CancellationTokenSource wystąpienie z każdym zadaniem. Jeśli wybierzesz przycisk Anuluj , anulujesz wszystkie zadania, które nie zostały jeszcze ukończone.

Pobieranie przykładu

Pełny projekt programu Windows Presentation Foundation (WPF) można pobrać z przykładu Async: Dostosowywanie aplikacji , a następnie wykonaj następujące kroki.

  1. Zdekompresuj pobrany plik, a następnie uruchom program Visual Studio.

  2. Na pasku menu wybierz pozycję Plik, Otwórz, Projekt/Rozwiązanie.

  3. W oknie dialogowym Otwieranie projektu otwórz folder zawierający zdekompresowany przykładowy kod, a następnie otwórz plik rozwiązania (.sln) dla pliku AsyncFineTuningVB.

  4. W Eksplorator rozwiązań otwórz menu skrótów dla projektu CancelAListOfTasks, a następnie wybierz pozycję Ustaw jako projekt startowy.

  5. Wybierz klucz F5, aby uruchomić projekt.

    Wybierz klawisze Ctrl+F5, aby uruchomić projekt bez debugowania.

Jeśli nie chcesz pobierać projektu, możesz przejrzeć pliki MainWindow.xaml.vb na końcu tego tematu.

Kompilowanie przykładu

Aby rozszerzyć przykład samodzielnie, postępuj zgodnie z instrukcjami w sekcji "Pobieranie przykładu", ale wybierz pozycję AnulujATask jako projekt startowy. Dodaj następujące zmiany do tego projektu. Gwiazdki oznaczają zmiany w programie.

  1. Dodaj metodę, aby utworzyć listę adresów internetowych.

    ' ***Add a method that creates a list of web addresses.
    Private Function SetUpURLList() As List(Of String)
    
        Dim urls = New List(Of String) From
            {
                "https://msdn.microsoft.com",
                "https://msdn.microsoft.com/library/hh290138.aspx",
                "https://msdn.microsoft.com/library/hh290140.aspx",
                "https://msdn.microsoft.com/library/dd470362.aspx",
                "https://msdn.microsoft.com/library/aa578028.aspx",
                "https://msdn.microsoft.com/library/ms404677.aspx",
                "https://msdn.microsoft.com/library/ff730837.aspx"
            }
        Return urls
    End Function
    
  2. Wywołaj metodę w pliku AccessTheWebAsync.

    ' ***Call SetUpURLList to make a list of web addresses.
    Dim urlList As List(Of String) = SetUpURLList()
    
  3. Dodaj następującą pętlę w pliku , AccessTheWebAsync aby przetworzyć każdy adres internetowy na liście.

    ' ***Add a loop to process the list of web addresses.
    For Each url In urlList
        ' GetAsync returns a Task(Of HttpResponseMessage).
        ' Argument ct carries the message if the Cancel button is chosen.
        ' ***Note that the Cancel button can cancel all remaining downloads.
        Dim response As HttpResponseMessage = Await client.GetAsync(url, ct)
    
        ' Retrieve the website contents from the HttpResponseMessage.
        Dim urlContents As Byte() = Await response.Content.ReadAsByteArrayAsync()
    
        resultsTextBox.Text &=
            vbCrLf & $"Length of the downloaded string: {urlContents.Length}." & vbCrLf
    Next
    
  4. Ponieważ AccessTheWebAsync wyświetla długość, metoda nie musi zwracać żadnych elementów. Usuń instrukcję return i zmień zwracany typ metody na Task zamiast Task<TResult>.

    Async Function AccessTheWebAsync(ct As CancellationToken) As Task
    

    Wywołaj metodę przy startButton_Click użyciu instrukcji zamiast wyrażenia.

    Await AccessTheWebAsync(cts.Token)
    
  5. Jeśli program nie zostanie anulowany, spowoduje to wygenerowanie następujących danych wyjściowych:

    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.
    

    Jeśli wybierzesz przycisk Anuluj przed zakończeniem pobierania, dane wyjściowe zawierają długość pobranych plików zakończonych przed anulowaniem.

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

Kompletne przykłady

Poniższe sekcje zawierają kod dla każdego z poprzednich przykładów. Zwróć uwagę, że należy dodać odwołanie dla elementu System.Net.Http.

Projekty można pobrać z przykładu asynchronicznego: dostrajanie aplikacji.

Anulowanie przykładu zadania

Poniższy kod jest kompletnym plikiem MainWindow.xaml.vb przykładu, który anuluje pojedyncze zadanie.

' Add an Imports directive and a reference for System.Net.Http.
Imports System.Net.Http

' Add the following Imports directive for System.Threading.
Imports System.Threading

Class MainWindow

    ' ***Declare a System.Threading.CancellationTokenSource.
    Dim cts As CancellationTokenSource

    Private Async Sub startButton_Click(sender As Object, e As RoutedEventArgs)
        ' ***Instantiate the CancellationTokenSource.
        cts = New CancellationTokenSource()

        resultsTextBox.Clear()

        Try
            ' ***Send a token to carry the message if cancellation is requested.
            Dim contentLength As Integer = Await AccessTheWebAsync(cts.Token)

            resultsTextBox.Text &=
                vbCrLf & $"Length of the downloaded string: {contentLength}." & vbCrLf

            ' *** If cancellation is requested, an OperationCanceledException results.
        Catch ex As OperationCanceledException
            resultsTextBox.Text &= vbCrLf & "Download canceled." & vbCrLf

        Catch ex As Exception
            resultsTextBox.Text &= vbCrLf & "Download failed." & vbCrLf
        End Try

        ' ***Set the CancellationTokenSource to Nothing when the download is complete.
        cts = Nothing
    End Sub

    ' ***Add an event handler for the Cancel button.
    Private Sub cancelButton_Click(sender As Object, e As RoutedEventArgs)

        If cts IsNot Nothing Then
            cts.Cancel()
        End If
    End Sub

    ' ***Provide a parameter for the CancellationToken.
    Async Function AccessTheWebAsync(ct As CancellationToken) As Task(Of Integer)

        Dim client As HttpClient = New HttpClient()

        resultsTextBox.Text &=
            vbCrLf & "Ready to download." & vbCrLf

        ' You might need to slow things down to have a chance to cancel.
        Await Task.Delay(250)

        ' GetAsync returns a Task(Of HttpResponseMessage).
        ' ***The ct argument carries the message if the Cancel button is chosen.
        Dim response As HttpResponseMessage = Await client.GetAsync("https://msdn.microsoft.com/library/dd470362.aspx", ct)

        ' Retrieve the website contents from the HttpResponseMessage.
        Dim urlContents As Byte() = Await response.Content.ReadAsByteArrayAsync()

        ' The result of the method is the length of the downloaded website.
        Return urlContents.Length
    End Function
End Class

' Output for a successful download:

' Ready to download.

' Length of the downloaded string: 158125.

' Or, if you cancel:

' Ready to download.

' Download canceled.

Anulowanie przykładu listy zadań

Poniższy kod to kompletny plik MainWindow.xaml.vb, na przykład, który anuluje listę zadań.

' Add an Imports directive and a reference for System.Net.Http.
Imports System.Net.Http

' Add the following Imports directive for System.Threading.
Imports System.Threading

Class MainWindow

    ' Declare a System.Threading.CancellationTokenSource.
    Dim cts As CancellationTokenSource

    Private Async Sub startButton_Click(sender As Object, e As RoutedEventArgs)

        ' Instantiate the CancellationTokenSource.
        cts = New CancellationTokenSource()

        resultsTextBox.Clear()

        Try
            ' ***AccessTheWebAsync returns a Task, not a Task(Of Integer).
            Await AccessTheWebAsync(cts.Token)
            '  ***Small change in the display lines.
            resultsTextBox.Text &= vbCrLf & "Downloads complete."

        Catch ex As OperationCanceledException
            resultsTextBox.Text &= vbCrLf & "Downloads canceled." & vbCrLf

        Catch ex As Exception
            resultsTextBox.Text &= vbCrLf & "Downloads failed." & vbCrLf
        End Try

        ' Set the CancellationTokenSource to Nothing when the download is complete.
        cts = Nothing
    End Sub

    ' Add an event handler for the Cancel button.
    Private Sub cancelButton_Click(sender As Object, e As RoutedEventArgs)

        If cts IsNot Nothing Then
            cts.Cancel()
        End If
    End Sub

    ' Provide a parameter for the CancellationToken.
    ' ***Change the return type to Task because the method has no return statement.
    Async Function AccessTheWebAsync(ct As CancellationToken) As Task

        Dim client As HttpClient = New HttpClient()

        ' ***Call SetUpURLList to make a list of web addresses.
        Dim urlList As List(Of String) = SetUpURLList()

        ' ***Add a loop to process the list of web addresses.
        For Each url In urlList
            ' GetAsync returns a Task(Of HttpResponseMessage).
            ' Argument ct carries the message if the Cancel button is chosen.
            ' ***Note that the Cancel button can cancel all remaining downloads.
            Dim response As HttpResponseMessage = Await client.GetAsync(url, ct)

            ' Retrieve the website contents from the HttpResponseMessage.
            Dim urlContents As Byte() = Await response.Content.ReadAsByteArrayAsync()

            resultsTextBox.Text &=
                vbCrLf & $"Length of the downloaded string: {urlContents.Length}." & vbCrLf
        Next
    End Function

    ' ***Add a method that creates a list of web addresses.
    Private Function SetUpURLList() As List(Of String)

        Dim urls = New List(Of String) From
            {
                "https://msdn.microsoft.com",
                "https://msdn.microsoft.com/library/hh290138.aspx",
                "https://msdn.microsoft.com/library/hh290140.aspx",
                "https://msdn.microsoft.com/library/dd470362.aspx",
                "https://msdn.microsoft.com/library/aa578028.aspx",
                "https://msdn.microsoft.com/library/ms404677.aspx",
                "https://msdn.microsoft.com/library/ff730837.aspx"
            }
        Return urls
    End Function

End Class

' Output if you do not choose to cancel:

' Length of the downloaded string: 35939.

' Length of the downloaded string: 237682.

' Length of the downloaded string: 128607.

' Length of the downloaded string: 158124.

' Length of the downloaded string: 204890.

' Length of the downloaded string: 175488.

' Length of the downloaded string: 145790.

' Downloads complete.

'  Sample output if you choose to cancel:

' Length of the downloaded string: 35939.

' Length of the downloaded string: 237682.

' Length of the downloaded string: 128607.

' Downloads canceled.

Zobacz też