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.
Dalam metode asinkron, tugas dimulai saat dibuat. Operator Tunggu diterapkan ke tugas pada titik dalam metode di mana pemrosesan tidak dapat dilanjutkan sampai tugas selesai. Seringkali tugas ditunggu segera setelah dibuat, seperti yang ditunjukkan contoh berikut.
Dim result = Await someWebAccessMethodAsync(url)
Namun, Anda dapat memisahkan pembuatan tugas dari menunggu tugas jika program Anda memiliki pekerjaan lain untuk diselesaikan yang tidak bergantung pada penyelesaian tugas.
' The following line creates and starts the task.
Dim myTask = someWebAccessMethodAsync(url)
' While the task is running, you can do other work that does not depend
' on the results of the task.
' . . . . .
' The application of Await suspends the rest of this method until the task is
' complete.
Dim result = Await myTask
Antara memulai tugas dan menunggunya, Anda dapat memulai tugas lain. Tugas tambahan secara implisit berjalan dalam mode paralel, tetapi tidak ada utas tambahan yang dibuat.
Program berikut memulai tiga unduhan web asinkron dan kemudian menunggunya dalam urutan di mana mereka dipanggil. Ketika Anda menjalankan program, perhatikan bahwa tugas tidak selalu selesai dalam urutan saat dibuat dan diharapkan selesai. Tugas tersebut mulai berjalan saat dibuat, dan satu atau beberapa tugas mungkin selesai sebelum metode mencapai ekspresi tunggu.
Nota
Untuk menyelesaikan proyek ini, Anda harus menginstal Visual Studio 2012 atau yang lebih tinggi dan .NET Framework 4.5 atau yang lebih tinggi di komputer Anda.
Untuk contoh lain yang memulai beberapa tugas secara bersamaan, lihat Cara: Memperluas Panduan Asinkron dengan Menggunakan Task.WhenAll (Visual Basic).
Anda dapat mengunduh kode untuk contoh ini dari Sampel Kode Pengembang.
Untuk menyiapkan proyek
Untuk menyiapkan aplikasi WPF, selesaikan langkah-langkah berikut. Anda dapat menemukan instruksi terperinci untuk langkah-langkah ini di Panduan: Mengakses Web dengan Menggunakan Asinkron dan Tunggu (Visual Basic).
Buat aplikasi WPF yang berisi kotak teks dan tombol. Beri nama tombol
startButton, dan beri nama kotakresultsTextBoxteks .Tambahkan referensi untuk System.Net.Http.
Dalam file MainWindow.xaml.vb, tambahkan
Importsstatement untukSystem.Net.Http.
Untuk menambahkan kode
Di jendela desain, MainWindow.xaml, klik dua kali tombol untuk membuat
startButton_Clickpenanganan aktivitas di MainWindow.xaml.vb.Salin kode berikut, dan tempelkan ke dalam isi
startButton_Clickdalam MainWindow.xaml.vb.resultsTextBox.Clear() Await CreateMultipleTasksAsync() resultsTextBox.Text &= vbCrLf & "Control returned to button1_Click."Kode ini memanggil metode asinkron,
CreateMultipleTasksAsync, yang mendorong aplikasi.Tambahkan metode dukungan berikut ke proyek:
ProcessURLAsyncHttpClient menggunakan metode untuk mengunduh konten situs web sebagai array byte. Metode dukungan,ProcessURLAsynclalu menampilkan dan mengembalikan panjang array.DisplayResultsmenampilkan jumlah byte dalam array byte untuk setiap URL. Tampilan ini menunjukkan kapan setiap tugas telah selesai diunduh.
Salin metode berikut, dan tempelkan setelah
startButton_Clickpenanganan aktivitas di MainWindow.xaml.vb.Private Async Function ProcessURLAsync(url As String, client As HttpClient) As Task(Of Integer) Dim byteArray = Await client.GetByteArrayAsync(url) DisplayResults(url, byteArray) Return byteArray.Length End Function Private Sub DisplayResults(url As String, content As Byte()) ' Display the length of each website. The string format ' is designed to be used with a monospaced font, such as ' Lucida Console or Global Monospace. Dim bytes = content.Length ' Strip off the "https://". Dim displayURL = url.Replace("https://", "") resultsTextBox.Text &= String.Format(vbCrLf & "{0,-58} {1,8}", displayURL, bytes) End SubTerakhir, tentukan metode
CreateMultipleTasksAsync, yang melakukan langkah-langkah berikut.Metode mendeklarasikan
HttpClientobjek, yang perlu Anda akses metode GetByteArrayAsync diProcessURLAsync.Metode ini membuat dan memulai tiga tugas jenis Task<TResult>, di mana
TResultadalah bilangan bulat. Saat setiap tugas selesai,DisplayResultsmenampilkan URL tugas dan panjang konten yang diunduh. Karena tugas berjalan secara asinkron, urutan di mana hasilnya muncul mungkin berbeda dari urutan di mana mereka dideklarasikan.Metode ini menunggu penyelesaian setiap tugas. Setiap
Awaitoperator menangguhkan eksekusiCreateMultipleTasksAsynchingga tugas yang ditunggu selesai. Operator juga mengambil nilai pengembalian dari panggilan keProcessURLAsyncdari setiap tugas yang diselesaikan.Ketika tugas telah selesai dan nilai bilangan bulat telah diambil, metode ini menjumlahkan panjang situs web dan menampilkan hasilnya.
Salin metode berikut, dan tempelkan ke dalam solusi Anda.
Private Async Function CreateMultipleTasksAsync() As Task ' Declare an HttpClient object, and increase the buffer size. The ' default buffer size is 65,536. Dim client As HttpClient = New HttpClient() With {.MaxResponseContentBufferSize = 1000000} ' Create and start the tasks. As each task finishes, DisplayResults ' displays its length. Dim download1 As Task(Of Integer) = ProcessURLAsync("https://msdn.microsoft.com", client) Dim download2 As Task(Of Integer) = ProcessURLAsync("https://msdn.microsoft.com/library/hh156528(VS.110).aspx", client) Dim download3 As Task(Of Integer) = ProcessURLAsync("https://msdn.microsoft.com/library/67w7t67f.aspx", client) ' Await each task. Dim length1 As Integer = Await download1 Dim length2 As Integer = Await download2 Dim length3 As Integer = Await download3 Dim total As Integer = length1 + length2 + length3 ' Display the total count for all of the websites. resultsTextBox.Text &= String.Format(vbCrLf & vbCrLf & "Total bytes returned: {0}" & vbCrLf, total) End FunctionPilih tombol F5 untuk menjalankan program, lalu pilih tombol Mulai .
Jalankan program beberapa kali untuk memverifikasi bahwa tiga tugas tidak selalu selesai dalam urutan yang sama dan bahwa urutan penyelesaiannya belum tentu sama dengan urutan pembuatan dan ketika tugas-tugas itu ditunggu-tunggu.
Contoh
Kode berikut berisi contoh lengkap.
' Add the following Imports statements, and add a reference for System.Net.Http.
Imports System.Net.Http
Class MainWindow
Async Sub startButton_Click(sender As Object, e As RoutedEventArgs) Handles startButton.Click
resultsTextBox.Clear()
Await CreateMultipleTasksAsync()
resultsTextBox.Text &= vbCrLf & "Control returned to button1_Click."
End Sub
Private Async Function CreateMultipleTasksAsync() As Task
' Declare an HttpClient object, and increase the buffer size. The
' default buffer size is 65,536.
Dim client As HttpClient =
New HttpClient() With {.MaxResponseContentBufferSize = 1000000}
' Create and start the tasks. As each task finishes, DisplayResults
' displays its length.
Dim download1 As Task(Of Integer) =
ProcessURLAsync("https://msdn.microsoft.com", client)
Dim download2 As Task(Of Integer) =
ProcessURLAsync("https://msdn.microsoft.com/library/hh156528(VS.110).aspx", client)
Dim download3 As Task(Of Integer) =
ProcessURLAsync("https://msdn.microsoft.com/library/67w7t67f.aspx", client)
' Await each task.
Dim length1 As Integer = Await download1
Dim length2 As Integer = Await download2
Dim length3 As Integer = Await download3
Dim total As Integer = length1 + length2 + length3
' Display the total count for all of the websites.
resultsTextBox.Text &= String.Format(vbCrLf & vbCrLf &
"Total bytes returned: {0}" & vbCrLf, total)
End Function
Private Async Function ProcessURLAsync(url As String, client As HttpClient) As Task(Of Integer)
Dim byteArray = Await client.GetByteArrayAsync(url)
DisplayResults(url, byteArray)
Return byteArray.Length
End Function
Private Sub DisplayResults(url As String, content As Byte())
' Display the length of each website. The string format
' is designed to be used with a monospaced font, such as
' Lucida Console or Global Monospace.
Dim bytes = content.Length
' Strip off the "https://".
Dim displayURL = url.Replace("https://", "")
resultsTextBox.Text &= String.Format(vbCrLf & "{0,-58} {1,8}", displayURL, bytes)
End Sub
End Class