Bagikan melalui


Batalkan Tugas Asinkron setelah Periode Waktu (Visual Basic)

Anda dapat membatalkan operasi asinkron setelah jangka waktu tertentu dengan menggunakan CancellationTokenSource.CancelAfter metode jika Anda tidak ingin menunggu operasi selesai. Metode ini menjadwalkan pembatalan tugas terkait yang tidak selesai dalam periode waktu yang ditentukan oleh CancelAfter ekspresi.

Contoh ini menambahkan ke kode yang dikembangkan di Batalkan Tugas Asinkron atau Daftar Tugas (Visual Basic) untuk mengunduh daftar situs web dan untuk menampilkan panjang konten masing-masing.

Nota

Untuk menjalankan contoh, Anda harus memasang Visual Studio 2012 atau yang lebih baru dan .NET Framework 4.5 atau yang lebih baru di komputer Anda.

Mengunduh Contoh

Anda dapat mengunduh proyek Windows Presentation Foundation (WPF) lengkap dari Async Sample: Fine Tuning Your Application lalu ikuti langkah-langkah berikut.

  1. Dekompresi file yang Anda unduh, lalu mulai Visual Studio.

  2. Pada bilah menu, pilih File, Buka, Proyek/Solusi.

  3. Dalam kotak dialog Buka Proyek , buka folder yang menyimpan kode sampel yang Anda dekompresi, lalu buka file solusi (.sln) untuk AsyncFineTuningVB.

  4. Di Penjelajah Solusi, buka menu pintasan untuk proyek CancelAfterTime , lalu pilih Atur sebagai Proyek StartUp.

  5. Pilih kunci F5 untuk menjalankan proyek.

    Pilih tombol Ctrl+F5 untuk menjalankan proyek tanpa men-debugnya.

  6. Jalankan program beberapa kali untuk memverifikasi bahwa output mungkin menampilkan output untuk semua situs web, tidak ada situs web, atau beberapa situs web.

Jika Anda tidak ingin mengunduh proyek, Anda dapat meninjau file MainWindow.xaml.vb di akhir topik ini.

Membangun Contoh

Contoh dalam topik ini menambahkan ke proyek yang dikembangkan di Batalkan Tugas Asinkron atau Daftar Tugas (Visual Basic) untuk membatalkan daftar tugas. Contohnya menggunakan UI yang sama, meskipun tombol Batalkan tidak digunakan secara eksplisit.

Untuk membuat contoh sendiri, langkah demi langkah, ikuti instruksi di bagian "Mengunduh Contoh", tetapi pilih CancelAListOfTasks sebagai Proyek StartUp. Tambahkan perubahan dalam topik ini ke proyek tersebut.

Untuk menentukan waktu maksimum sebelum tugas ditandai sebagai dibatalkan, tambahkan panggilan ke CancelAfterstartButton_Click, seperti yang ditunjukkan contoh berikut. Penambahan ditandai dengan tanda bintang.

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

Jalankan program beberapa kali untuk memverifikasi bahwa output mungkin menampilkan output untuk semua situs web, tidak ada situs web, atau beberapa situs web. Output berikut adalah sampel:

Length of the downloaded string: 35990.

Length of the downloaded string: 407399.

Length of the downloaded string: 226091.

Downloads canceled.

Contoh Lengkap

Kode berikut adalah teks lengkap file MainWindow.xaml.vb untuk contoh. Tanda bintang menandai elemen yang ditambahkan untuk contoh ini.

Perhatikan bahwa Anda harus menambahkan referensi untuk System.Net.Http.

Anda dapat mengunduh proyek dari Sampel Asinkron: Menyempurnakan Aplikasi Anda.

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

Lihat juga