Catatan
Akses ke halaman ini memerlukan otorisasi. Anda dapat mencoba masuk atau mengubah direktori.
Akses ke halaman ini memerlukan otorisasi. Anda dapat mencoba mengubah direktori.
Anda dapat menyiapkan tombol yang dapat Anda gunakan untuk membatalkan aplikasi asinkron jika Anda tidak ingin menunggunya selesai. Dengan mengikuti contoh dalam topik ini, Anda dapat menambahkan tombol pembatalan ke aplikasi yang mengunduh konten satu situs web atau daftar situs web.
Berikut ini adalah contoh penggunaan UI yang dijelaskan oleh Fine-Tuning Aplikasi Asinkron Anda (Visual Basic).
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.
Batalkan Tugas
Contoh pertama mengaitkan tombol Batalkan dengan satu tugas unduhan. Jika Anda memilih tombol saat aplikasi mengunduh konten, unduhan dibatalkan.
Mengunduh Contoh
Anda dapat mengunduh proyek Windows Presentation Foundation (WPF) lengkap dari Async Sample: Fine Tuning Your Application lalu ikuti langkah-langkah berikut.
Dekompresi file yang Anda unduh, lalu mulai Visual Studio.
Pada bilah menu, pilih File, Buka, Proyek/Solusi.
Dalam kotak dialog Buka Proyek , 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 StartUp.
Pilih kunci F5 untuk menjalankan proyek.
Pilih tombol Ctrl+F5 untuk menjalankan proyek tanpa men-debugnya.
Jika Anda tidak ingin mengunduh proyek, Anda dapat meninjau file MainWindow.xaml.vb di akhir topik ini.
Membangun Contoh
Perubahan berikut menambahkan tombol Batal ke aplikasi yang mengunduh situs web. Jika Anda tidak ingin mengunduh atau membuat contoh, Anda dapat meninjau produk akhir di bagian "Contoh Lengkap" di akhir topik ini. Tanda bintang menandai perubahan dalam kode.
Untuk membuat contoh sendiri, langkah demi langkah, ikuti instruksi di bagian "Mengunduh Contoh", tetapi pilih StarterCode sebagai Proyek StartUp alih-alih CancelATask.
Kemudian tambahkan perubahan berikut ke file MainWindow.xaml.vb proyek tersebut.
Deklarasikan
CancellationTokenSource
variabel,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 . Pengendali acara 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 di penanganan aktivitas untuk tombol Mulai ,
startButton_Click
.Instansikan
CancellationTokenSource
,cts
.' ***Instantiate the CancellationTokenSource. cts = New CancellationTokenSource()
Dalam pemanggilan ke
AccessTheWebAsync
, yang berfungsi untuk mengunduh konten dari situs web tertentu, kirimkan properti CancellationTokenSource.Token daricts
sebagai argumen. PropertiToken
menyebarluaskan pesan jika pembatalan diminta. Tambahkan blok tangkapan yang menampilkan pesan jika pengguna memilih untuk membatalkan operasi pengunduhan. Kode berikut menunjukkan perubahan.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 HttpClient.GetAsync(String, CancellationToken) kelebihan bebanGetAsync
metode dalam HttpClient jenis 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, program akan menghasilkan output berikut:
Ready to download. Length of the downloaded string: 158125.
Jika Anda memilih tombol Batal sebelum program selesai mengunduh konten, program akan menghasilkan output berikut:
Ready to download. Download canceled.
Batalkan Daftar Tugas
Anda dapat memperluas contoh sebelumnya untuk membatalkan banyak tugas dengan mengaitkan instans yang sama CancellationTokenSource
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 Async Sample: Fine Tuning Your Application lalu ikuti langkah-langkah berikut.
Dekompresi file yang Anda unduh, lalu mulai Visual Studio.
Pada bilah menu, pilih File, Buka, Proyek/Solusi.
Dalam kotak dialog Buka Proyek , 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 StartUp.
Pilih kunci F5 untuk menjalankan proyek.
Pilih tombol Ctrl+F5 untuk menjalankan proyek tanpa men-debugnya.
Jika Anda tidak ingin mengunduh proyek, Anda dapat meninjau file MainWindow.xaml.vb di akhir topik ini.
Membangun Contoh
Untuk memperluas contoh sendiri, langkah demi langkah, ikuti instruksi di bagian "Mengunduh Contoh", tetapi pilih CancelATask sebagai Proyek StartUp. 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 di
AccessTheWebAsync
.' ***Call SetUpURLList to make a list of web addresses. Dim urlList As List(Of String) = SetUpURLList()
Tambahkan perulangan
AccessTheWebAsync
berikut 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 mengembalikan apa pun. Hapus pernyataan pengembalian, dan ubah jenis pengembalian 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, program akan menghasilkan output 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, output 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: Menyempurnakan 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.
Batalkan 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.