Membatalkan Tugas atau Daftar Tugas Asinkron (Visual Basic)
Anda dapat menyiapkan tombol yang dapat Anda gunakan untuk membatalkan aplikasi asinkron jika Anda tidak ingin menunggunya hingga selesai. Dengan mengikuti contoh dalam topik ini, Anda dapat menambahkan tombol pembatalan ke aplikasi yang mengunduh konten satu situs web atau daftar situs web.
Contoh ini menggunakan UI yang dijelaskan Penyempurnaan Aplikasi Asinkron Anda (Visual Basic).
Catatan
Untuk menjalankan contoh, Anda harus memiliki Visual Studio 2012 atau yang lebih baru dan .NET Framework 4.5 atau yang lebih baru terinstal di komputer Anda.
Membatalkan Tugas
Contoh pertama mengaitkan tombol Batalkan dengan satu tugas unduhan. Jika Anda memilih tombol sembari aplikasi mengunduh konten, unduhan dibatalkan.
Mengunduh Contoh
Anda dapat mengunduh proyek Windows Presentation Foundation (WPF) lengkap dari Sampel Asinkron: Menyempurnakan Aplikasi Anda lalu ikuti langkah-langkah berikut.
Dekompresi file yang Anda unduh, lalu mulai Visual Studio.
Pada bilah menu, pilih File, Buka, Project/Solusi.
Dalam kotak dialog Buka Project, buka folder yang menyimpan kode sampel yang Anda dekompresi, lalu buka file solusi (.sln) untuk AsyncFineTuningVB.
Di Penjelajah Solusi, buka menu pintasan untuk proyek CancelATask, lalu pilih Atur sebagai Proyek Pengaktifan.
Pilih kunci F5 untuk menjalankan proyek.
Pilih tombol Ctrl+F5 untuk menjalankan proyek tanpa penelusuran kesalahan.
Jika Anda tidak ingin mengunduh proyek, Anda dapat mengulas file MainWindow.xaml.vb di akhir topik ini.
Membangun Contoh
Perubahan berikut menambahkan tombol Batalkan ke aplikasi yang mengunduh situs web. Jika Anda tidak ingin mengunduh atau membangun contoh, Anda dapat mengulas produk akhir dalam bagian "Contoh Lengkap" di akhir topik ini. Tanda bintang menandai perubahan dalam kode.
Untuk membangun contoh sendiri, langkah demi langkah, ikuti instruksi dalam bagian "Pengunduhan Contoh", tetapi pilih StarterCode sebagai Proyek Pengaktifan alih-alih CancelATask.
Lalu tambahkan perubahan berikut ke file MainWindow.xaml.vb dari proyek tersebut.
Nyatakan variabel
CancellationTokenSource
,cts
, yang berada dalam cakupan untuk semua metode yang mengaksesnya.Class MainWindow ' ***Declare a System.Threading.CancellationTokenSource. Dim cts As CancellationTokenSource
Tambahkan penanganan aktivitas berikut untuk tombol Batalkan. Penanganan aktivitas menggunakan metode CancellationTokenSource.Cancel untuk memberi tahu
cts
saat pengguna meminta pembatalan.' ***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
Buat perubahan berikut dalam penanganan aktivitas untuk tombol Mulai,
startButton_Click
.Buat objek
CancellationTokenSource
,cts
.' ***Instantiate the CancellationTokenSource. cts = New CancellationTokenSource()
Dalam panggilan ke
AccessTheWebAsync
, yang mengunduh konten situs web tertentu, kirim properti CancellationTokenSource.Token daricts
sebagai argumen. PropertiToken
menyebarkan pesan jika pembatalan diminta. Tambahkan blok tangkapan yang menampilkan pesan jika pengguna memilih untuk membatalkan operasi pengunduhan. Kode berikut menunjukkan perubahan tersebut.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
Dalam
AccessTheWebAsync
, gunakan kelebihan beban HttpClient.GetAsync(String, CancellationToken) dari metodeGetAsync
dalam jenis HttpClient untuk mengunduh konten situs web. Teruskanct
, parameter CancellationToken dariAccessTheWebAsync
, sebagai argumen kedua. Token membawa pesan jika pengguna memilih tombol Batalkan.Kode berikut menunjukkan perubahan dalam
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
Jika Anda tidak membatalkan program, ia menghasilkan keluaran berikut:
Ready to download. Length of the downloaded string: 158125.
Jika Anda memilih tombol Batalkan sebelum program selesai mengunduh konten, program menghasilkan keluaran berikut:
Ready to download. Download canceled.
Membatalkan Daftar Tugas
Anda dapat memperluas contoh sebelumnya untuk membatalkan banyak tugas dengan mengaitkan instans CancellationTokenSource
yang sama dengan setiap tugas. Jika Anda memilih tombol Batalkan, Anda membatalkan semua tugas yang belum selesai.
Mengunduh Contoh
Anda dapat mengunduh proyek Windows Presentation Foundation (WPF) lengkap dari Sampel Asinkron: Menyempurnakan Aplikasi Anda lalu ikuti langkah-langkah berikut.
Dekompresi file yang Anda unduh, lalu mulai Visual Studio.
Pada bilah menu, pilih File, Buka, Project/Solusi.
Dalam kotak dialog Buka Project, buka folder yang menyimpan kode sampel yang Anda dekompresi, lalu buka file solusi (.sln) untuk AsyncFineTuningVB.
Di Penjelajah Solusi, buka menu pintasan untuk proyek CancelAListOfTasks, lalu pilih Atur sebagai Proyek Pengaktifan.
Pilih kunci F5 untuk menjalankan proyek.
Pilih tombol Ctrl+F5 untuk menjalankan proyek tanpa penelusuran kesalahan.
Jika Anda tidak ingin mengunduh proyek, Anda dapat mengulas file MainWindow.xaml.vb di akhir topik ini.
Membangun Contoh
Untuk memperluas contoh sendiri, langkah demi langkah, ikuti instruksi dalam bagian "Pengunduhan Contoh", tetapi pilih CancelATask sebagai Proyek Pengaktifan. Tambahkan perubahan berikut ke proyek tersebut. Tanda bintang menandai perubahan dalam program.
Tambahkan metode untuk membuat daftar alamat web.
' ***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
Panggil metode dalam
AccessTheWebAsync
.' ***Call SetUpURLList to make a list of web addresses. Dim urlList As List(Of String) = SetUpURLList()
Tambahkan perulangan berikut dalam
AccessTheWebAsync
untuk memproses setiap alamat web dalam daftar.' ***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
Karena
AccessTheWebAsync
menampilkan panjangnya, metode tidak perlu menampilkan apa pun. Hapus pernyataan tampilan, dan ubah jenis tampilan metode menjadi Task alih-alih Task<TResult>.Async Function AccessTheWebAsync(ct As CancellationToken) As Task
Panggil metode dari
startButton_Click
dengan menggunakan pernyataan alih-alih ekspresi.Await AccessTheWebAsync(cts.Token)
Jika Anda tidak membatalkan program, ia menghasilkan keluaran berikut:
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.
Jika Anda memilih tombol Batalkan sebelum unduhan selesai, keluaran berisi panjang unduhan yang selesai sebelum pembatalan.
Length of the downloaded string: 35939. Length of the downloaded string: 237682. Length of the downloaded string: 128607. Downloads canceled.
Contoh Lengkap
Bagian berikut berisi kode untuk setiap contoh sebelumnya. Perhatikan bahwa Anda harus menambahkan referensi untuk System.Net.Http.
Anda dapat mengunduh proyek dari Sampel Asinkron: Penyempurnaan Aplikasi Anda.
Membatalkan Contoh Tugas
Kode berikut adalah file MainWindow.xaml.vb lengkap untuk contoh yang membatalkan satu tugas.
' 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.
Membatalkan Contoh Daftar Tugas
Kode berikut adalah file MainWindow.xaml.vb lengkap untuk contoh yang membatalkan daftar tugas.
' 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.
Lihat juga
Saran dan Komentar
https://aka.ms/ContentUserFeedback.
Segera hadir: Sepanjang tahun 2024 kami akan menghentikan penggunaan GitHub Issues sebagai mekanisme umpan balik untuk konten dan menggantinya dengan sistem umpan balik baru. Untuk mengetahui informasi selengkapnya, lihat:Kirim dan lihat umpan balik untuk