Share via


Zaman Uyumsuz Görevleri Bir Süre Sonra İ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, ifade tarafından belirlenen süre içinde tamamlanmamış ilişkili görevlerin iptalini CancelAfter zamanlar.

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.

Not

Ö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 dosyanın sıkıştırmasını açın ve Visual Studio'yu başlatın.

  2. Menü çubuğunda Dosya, Aç, 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'da CancelAfterTime 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.

  6. Çıkışın tüm web siteleri, web siteleri veya bazı web siteleri için çıkış gösterebileceğini doğrulamak için programı birkaç kez çalıştırın.

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

Örneği Oluşturma

Bu konudaki örnek, bir görev listesini iptal etmek için Zaman Uyumsuz Görevi İptal Etme veya Görev Listesi (Visual Basic) bölümünde geliştirilen projeye eklenir. İ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 öğesine startButton_Clickbir çağrı CancelAfter 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

Çıkışın tüm web siteleri, web siteleri veya bazı web siteleri için çıkış gösterebileceğini doğrulamak için programı birkaç kez çalıştırı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.

için System.Net.Httpbir başvuru eklemeniz gerektiğine dikkat edin.

Projeyi Zaman Uyumsuz Örnek: Uygulamanızda İnce Ayarlama'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 bkz.