Aracılığıyla paylaş


Belirli Bir Süre Sonra Asenkron Görevleri İptal Etme (Visual Basic)

İşlemin bitmesini beklemek istemiyorsanız yöntemini kullanarak CancellationTokenSource.CancelAfter zaman uyumsuz bir işlemi belirli bir süre sonra iptal edebilirsiniz. Bu yöntem, CancelAfter ifadesi tarafından belirlenen zaman dilimi içinde tamamlanmamış ilişkili görevlerin iptalini planlar.

Bu örnek, web sitelerinin listesini indirmek ve her birinin içeriğinin uzunluğunu görüntülemek için Zaman Uyumsuz Görevi İptal Etme veya Görev Listesi (Visual Basic) içinde geliştirilen koda ekler.

Uyarı

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

Ö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'ndeCancelAfterTime projesinin kısayol menüsünü açın ve 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.

  6. Programı birkaç kez çalıştırarak, çıktının tüm web siteleri için, hiçbir web sitesi için veya bazı web siteleri için olabileceğini doğrulayın.

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

Örneği Oluşturma

Bu konudaki örnek, Zaman Uyumsuz Görevi veya Görev Listesini İptal Etme (Visual Basic) bölümünde geliştirilmiş projeye katkıda bulunarak bir görev listesini iptal etmeyi sağlar. İptal düğmesi açıkça kullanılmasa da örnek aynı kullanıcı arabirimini kullanır.

Örneği kendiniz oluşturmak için, adım adım "Örneği İndirme" bölümündeki yönergeleri izleyin, ancak StartUp Projesi olarak CancelAListOfTasks'i seçin. Bu konudaki değişiklikleri bu projeye ekleyin.

Görevler iptal edildi olarak işaretlenmeden önce en uzun süreyi belirtmek için, aşağıdaki örnekte gösterildiği gibi CancelAfter öğesine bir çağrı startButton_Click ekleyin. Ekleme, yıldız işaretiyle işaretlenir.

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

    ' Instantiate the CancellationTokenSource.
    cts = New CancellationTokenSource()

    resultsTextBox.Clear()

    Try
        ' ***Set up the CancellationTokenSource to cancel after 2.5 seconds. (You
        ' can adjust the time.)
        cts.CancelAfter(2500)

        Await AccessTheWebAsync(cts.Token)
        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

Programı birkaç kez çalıştırarak, çıktının tüm web siteleri için, hiçbir web sitesi için veya bazı web siteleri için olabileceğini doğrulayın. Aşağıdaki çıkış bir örnektir:

Length of the downloaded string: 35990.

Length of the downloaded string: 407399.

Length of the downloaded string: 226091.

Downloads canceled.

Tam Örnek

Aşağıdaki kod, örnek için MainWindow.xaml.vb dosyasının tam metnidir. Yıldız işaretleri, bu örnek için eklenen öğeleri işaretler.

Dikkat edin, System.Net.Http için bir referans eklemeniz gerekiyor.

Projeyi Asenkron Örnek: Uygulamanıza Hassas Ayar Yapma'dan indirebilirsiniz.

' 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
            ' ***Set up the CancellationTokenSource to cancel after 2.5 seconds. (You
            ' can adjust the time.)
            cts.CancelAfter(2500)

            Await AccessTheWebAsync(cts.Token)
            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

    ' You can still include a Cancel button if you want to.
    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()

        ' Process each element in 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

' Sample output:

' Length of the downloaded string: 35990.

' Length of the downloaded string: 407399.

' Length of the downloaded string: 226091.

' Downloads canceled.

Ayrıca bakınız