Aracılığıyla paylaş


Zaman Uyumsuz Görevi veya Görev Listesini İptal Etme (Visual Basic)

Bir asenkron uygulamanın bitmesini beklemek istemiyorsanız, iptal etmek için kullanabileceğiniz bir düğme ayarlayabilirsiniz. Bu konudaki örnekleri izleyerek, bir web sitesinin içeriğini veya bir web sitesi listesini indiren bir uygulamaya iptal düğmesi ekleyebilirsiniz.

Örnekler, Fine-Tuning Zaman Uyumsuz Uygulamanız (Visual Basic) tarafından açıklanan kullanıcı arabirimini kullanır.

Uyarı

Örnekleri çalıştırmak için bilgisayarınızda Visual Studio 2012 veya üzeri ve .NET Framework 4.5 veya daha yeni bir sürümü yüklü olmalıdır.

Görevi İptal Etme

İlk örnek , İptal düğmesini tek bir indirme göreviyle ilişkilendirir. Uygulama içerik indirirken düğmeyi seçerseniz indirme iptal edilir.

Örneği İndirme

Windows Presentation Foundation (WPF) projesinin tamamını Async Sample: Fine Tuning Your Application adresinden indirebilir ve ardından aşağıdaki adımları izleyebilirsiniz.

  1. İndirdiğiniz dosyayı açarak sıkıştırılmış halini çözün ve ardından Visual Studio'yu başlatın.

  2. Menü çubuğunda Dosya, , Proje/Çözüm'e tıklayın.

  3. Projeyi Aç iletişim kutusunda, sıkıştırmasını kaldırdığınız örnek kodun bulunduğu klasörü açın ve ardından AsyncFineTuningVB için çözüm (.sln) dosyasını açın.

  4. Çözüm Gezgini'ndeCancelATask projesinin kısayol menüsünü açın ve ardından Başlangıç Projesi Olarak Ayarla'yı seçin.

  5. Projeyi çalıştırmak için F5 anahtarını seçin.

    Projeyi hata ayıklamadan çalıştırmak için Ctrl+F5 tuşlarını seçin.

Projeyi indirmek istemiyorsanız, bu konunun sonundaki MainWindow.xaml.vb dosyalarını gözden geçirebilirsiniz.

Örneği Oluşturma

Aşağıdaki değişiklikler, web sitesini indiren bir uygulamaya İptal düğmesi ekler. Örneği indirmek veya derlemek istemiyorsanız, bu konunun sonundaki "Tam Örnekler" bölümünde son ürünü gözden geçirebilirsiniz. Yıldız işaretleri koddaki değişiklikleri işaretler.

Örneği kendiniz oluşturmak için, adım adım "Örneği İndirme" bölümündeki yönergeleri izleyin, ancak CancelATask yerine Başlangıç Projesi olarak StarterCode'u seçin.

Ardından aşağıdaki değişiklikleri projenin MainWindow.xaml.vb dosyasına ekleyin.

  1. Erişen tüm yöntemlerin kapsamında olan bir CancellationTokenSource değişken ctsbildirin.

    Class MainWindow
    
        ' ***Declare a System.Threading.CancellationTokenSource.
        Dim cts As CancellationTokenSource
    
  2. İptal düğmesi için aşağıdaki olay işleyicisini ekleyin. Olay işleyicisi, kullanıcı iptali istediğinde CancellationTokenSource.Cancel bildirimde bulunmak için cts yöntemini kullanır.

    ' ***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. Başlangıç düğmesi için olay işleyicisinde aşağıdaki değişiklikleri yapın: startButton_Click.

    • CancellationTokenSource ve cts örneklerini oluştur.

      ' ***Instantiate the CancellationTokenSource.
      cts = New CancellationTokenSource()
      
    • Belirtilen bir web sitesinin içeriğini indiren AccessTheWebAsync çağrısında, CancellationTokenSource.Token öğesinin cts özelliğini bağımsız değişken olarak gönderin. Özellik Token, iptal istenirse mesajı yayar. Kullanıcı indirme işlemini iptal etmeyi seçerse ileti görüntüleyen bir catch bloğu ekleyin. Aşağıdaki kod değişiklikleri gösterir.

      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. AccessTheWebAsync içinde, bir web sitesinin içeriğini indirmek için, HttpClient.GetAsync(String, CancellationToken) türündeki GetAsync yönteminin HttpClient aşırı yüklemesini kullanın. ct'in CancellationToken parametresini, ikinci bağımsız değişken olarak AccessTheWebAsync'ı geçirin. Kullanıcı İptal düğmesini seçerse belirteç iletiyi taşır.

    Aşağıdaki kod, içindeki AccessTheWebAsyncdeğişiklikleri gösterir.

    ' ***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. Programı iptal etmediyseniz, aşağıdaki çıkışı üretir:

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

    Program içeriği indirmeyi bitirmeden önce İptal düğmesini seçerseniz, program aşağıdaki çıkışı üretir:

    Ready to download.
    Download canceled.
    

Görev Listesini İptal Etme

Aynı örneği her görevle ilişkilendirerek CancellationTokenSource birçok görevi iptal etmek için önceki örneği genişletebilirsiniz. İptal düğmesini seçerseniz, henüz tamamlanmamış tüm görevleri iptal edebilirsiniz.

Örneği İndirme

Windows Presentation Foundation (WPF) projesinin tamamını Async Sample: Fine Tuning Your Application adresinden indirebilir ve ardından aşağıdaki adımları izleyebilirsiniz.

  1. İndirdiğiniz dosyayı açarak sıkıştırılmış halini çözün ve ardından Visual Studio'yu başlatın.

  2. Menü çubuğunda Dosya, , Proje/Çözüm'e tıklayın.

  3. Projeyi Aç iletişim kutusunda, sıkıştırmasını kaldırdığınız örnek kodun bulunduğu klasörü açın ve ardından AsyncFineTuningVB için çözüm (.sln) dosyasını açın.

  4. Çözüm Gezgini'ndeCancelAListOfTasks projesinin kısayol menüsünü açın ve ardından StartUp Projesi Olarak Ayarla'yı seçin.

  5. Projeyi çalıştırmak için F5 anahtarını seçin.

    Projeyi hata ayıklamadan çalıştırmak için Ctrl+F5 tuşlarını seçin.

Projeyi indirmek istemiyorsanız, bu konunun sonundaki MainWindow.xaml.vb dosyalarını gözden geçirebilirsiniz.

Örneği Oluşturma

Örneği kendiniz genişletmek için, adım adım "Örneği İndirme" bölümündeki yönergeleri izleyin, ancak StartUp Projesi olarak CancelATask'i seçin. Bu projeye aşağıdaki değişiklikleri ekleyin. Yıldız işaretleri programdaki değişiklikleri işaretler.

  1. Web adreslerinin listesini oluşturmak için bir yöntem ekleyin.

    ' ***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. Metodu AccessTheWebAsync içinde çağırın.

    ' ***Call SetUpURLList to make a list of web addresses.
    Dim urlList As List(Of String) = SetUpURLList()
    
  3. Listedeki her web adresini işlemek için aşağıdaki döngünün AccessTheWebAsync içine ekleyin.

    ' ***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. Uzunlukları görüntülediğinden AccessTheWebAsync yöntemin herhangi bir şey döndürmesi gerekmez. return deyimini kaldırın ve yöntemin dönüş türünü Task yerine Task<TResult> olarak değiştirin.

    Async Function AccessTheWebAsync(ct As CancellationToken) As Task
    

    Yöntemi startButton_Click ile çağırırken, bir anlam yerine bir ifade kullanın.

    Await AccessTheWebAsync(cts.Token)
    
  5. Programı iptal etmediyseniz, aşağıdaki çıkışı üretir:

    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.
    

    İndirmeler tamamlanmadan önce İptal düğmesini seçerseniz çıkış, iptalden önce tamamlanan indirmelerin uzunluklarını içerir.

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

Tam Örnekler

Aşağıdaki bölümlerde önceki örneklerin her birinin kodu yer alır. Dikkat edin, System.Net.Http için bir referans eklemeniz gerekiyor.

Projeleri Asenkron Örnek: Uygulamanızı Optimize Etme'den indirebilirsiniz.

Görev Örneğini İptal Etme

Aşağıdaki kod, tek bir görevi iptal eden örneğin tam MainWindow.xaml.vb dosyasıdır.

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

Görev Listesini İptal Etme Örneği

Aşağıdaki kod, görev listesini iptal eden örneğin tam MainWindow.xaml.vb dosyasıdır.

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

Ayrıca bakınız