Procedura: effettuare più richieste Web in parallelo (C# e Visual Basic)
In un metodo async, le attività vengono avviate quando vengono creati.L'operatore Attendere (Visual Basic) o attendere (C#) viene applicata all'attività nel punto del metodo in cui l'elaborazione non può continuare finché l'attività non viene completata.Un'attività è in attesa spesso non appena creato, come illustrato di seguito.
Dim result = Await someWebAccessMethodAsync(url)
var result = await someWebAccessMethodAsync(url);
Tuttavia, è possibile separare creare l'attività da attendere l'attività se il programma ha altre attività da svolgere che non dipende dal completamento dell'attività.
' 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
// The following line creates and starts the task.
var myTask = someWebAccessMethodAsync(url);
// While the task is running, you can do other work that doesn't depend
// on the results of the task.
// . . . . .
// The application of await suspends the rest of this method until the task is complete.
var result = await myTask;
Tra avviare un'attività e attenderla, è possibile avviare altre attività.Attività aggiuntive in modo implicito in parallelo, ma nessun thread aggiuntivo viene creato.
I seguenti inizio del programma tre download asincroni il web e li attesa nell'ordine in cui sono chiamate.Avviso, quando si esegue il programma, che le attività non vengano sempre nell'ordine in cui vengono creati e attende.Verranno eseguiti quando vengono creati e uno o più delle attività potrebbero essere completata prima che il metodo raggiungesse le espressioni di attesa.
Per un altro esempio in cui inizia più attività contemporaneamente, vedere Procedura: estendere la procedura dettagliata tramite Task.WhenAll (C# e Visual Basic).
Per completare il progetto, è necessario disporre Visual Studio 2012 installato nel computer.Per ulteriori informazioni, vedere il sito Web Microsoft.
È possibile scaricare il codice di questo esempio da Esempi di codice dello sviluppatore.
Per impostare il progetto
Per installare un'applicazione WPF, completare i passaggi seguenti.È possibile trovare istruzioni dettagliate per questi passaggi in Procedura dettagliata: accesso al Web tramite Async e Await (C# e Visual Basic).
Creare un'applicazione WPF che contiene una casella di testo e un pulsante.Denominare il pulsante startButtone denominare la casella di testo resultsTextBox.
Aggiungere un riferimento per System.Net.Http.
In MainWindow.xaml.vb o MainWindow.xaml.cs, aggiungere un'istruzione Imports o una direttiva using per System.Net.Http.
Per aggiungere il codice
Nell'elaborazione di parametri, MainWindow.xaml, fare doppio clic sul pulsante per creare il gestore eventi startButton_Click in MainWindow.xaml.vb o MainWindow.xaml.cs.In alternativa, selezionare il pulsante, selezionare l'icona gestori eventi per gli elementi selezionati nella finestra Proprietà quindi immettere startButton_Click nella casella di testo Fare clic.
Copiare il codice seguente e incollarlo nel corpo startButton_Click in MainWindow.xaml.vb o MainWindow.xaml.cs.
resultsTextBox.Clear() Await CreateMultipleTasksAsync() resultsTextBox.Text &= vbCrLf & "Control returned to button1_Click."
resultsTextBox.Clear(); await CreateMultipleTasksAsync(); resultsTextBox.Text += "\r\n\r\nControl returned to startButton_Click.\r\n";
Il codice chiama un metodo asincrono, CreateMultipleTasksAsync, che determina l'applicazione.
Aggiungere i seguenti metodi di supporto al progetto:
ProcessURLAsync utilizza un metodo HttpClient per scaricare il contenuto di un sito Web come matrice di byte.Il metodo di supporto, ProcessURLAsync visualizzare e restituisce la lunghezza della matrice.
DisplayResults visualizza il numero di byte nella matrice di byte per ciascun URL.In questa visualizzazione quando un'attività ha completato il download.
Copiare i seguenti metodi e incollili dopo il gestore eventi startButton_Click in MainWindow.xaml.vb o MainWindow.xaml.cs.
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 "http://". Dim displayURL = url.Replace("http://", "") resultsTextBox.Text &= String.Format(vbCrLf & "{0,-58} {1,8}", displayURL, bytes) End Sub
async Task<int> ProcessURLAsync(string url, HttpClient client) { var byteArray = await client.GetByteArrayAsync(url); DisplayResults(url, byteArray); return byteArray.Length; } private void DisplayResults(string url, byte[] content) { // 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. var bytes = content.Length; // Strip off the "http://". var displayURL = url.Replace("http://", ""); resultsTextBox.Text += string.Format("\n{0,-58} {1,8}", displayURL, bytes); }
Infine, definire il metodo CreateMultipleTasksAsync, che esegue le operazioni seguenti.
Il metodo dichiara un oggetto HttpClient, che sono necessari del metodo di accesso GetByteArrayAsync in ProcessURLAsync.
Il metodo crea e avvia tre attività di tipo Task<TResult>, in cui TResult è un Integer.Mentre completamento di ogni attività, DisplayResults visualizzato l'url e la durata dell'attività del contenuto scaricati.Poiché le attività vengono eseguite in modo asincrono, l'ordine in cui i risultati vengono visualizzati potrebbero differire dall'ordine in cui sono stati dichiarati.
Il metodo attende il completamento di ogni attività.Ogni operatore await o Await sospende l'esecuzione CreateMultipleTasksAsync fino a completare l'attività attesa.L'operatore recupera anche il valore restituito dalla chiamata a ProcessURLAsync da ogni attività completata.
Quando le attività sono state completate e i valori Integer sono stati recuperati, il metodo somma delle lunghezze dei siti Web e viene visualizzato il risultato.
Copiare il seguente metodo e incollarlo nella soluzione.
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/en-us/library/hh156528(VS.110).aspx", client) Dim download3 As Task(Of Integer) = ProcessURLAsync("https://msdn.microsoft.com/en-us/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 Task CreateMultipleTasksAsync() { // Declare an HttpClient object, and increase the buffer size. The // default buffer size is 65,536. HttpClient client = new HttpClient() { MaxResponseContentBufferSize = 1000000 }; // Create and start the tasks. As each task finishes, DisplayResults // displays its length. Task<int> download1 = ProcessURLAsync("https://msdn.microsoft.com", client); Task<int> download2 = ProcessURLAsync("https://msdn.microsoft.com/en-us/library/hh156528(VS.110).aspx", client); Task<int> download3 = ProcessURLAsync("https://msdn.microsoft.com/en-us/library/67w7t67f.aspx", client); // Await each task. int length1 = await download1; int length2 = await download2; int length3 = await download3; int total = length1 + length2 + length3; // Display the total count for the downloaded websites. resultsTextBox.Text += string.Format("\r\n\r\nTotal bytes returned: {0}\r\n", total); }
Scegliere il tasto F5 per eseguire il programma e quindi scegliere il pulsante Avvia.
Eseguire il programma più volte per verificare che le tre attività non completare sempre nello stesso ordine e che l'ordine in cui vengono completati non è necessariamente l'ordine in cui vengano creati e attesi.
Esempio
Il codice seguente include l'esempio completo.
' 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/en-us/library/hh156528(VS.110).aspx", client)
Dim download3 As Task(Of Integer) =
ProcessURLAsync("https://msdn.microsoft.com/en-us/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 "http://".
Dim displayURL = url.Replace("http://", "")
resultsTextBox.Text &= String.Format(vbCrLf & "{0,-58} {1,8}", displayURL, bytes)
End Sub
End Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
// Add the following using directive, and add a reference for System.Net.Http.
using System.Net.Http;
namespace AsyncExample_MultipleTasks
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private async void startButton_Click(object sender, RoutedEventArgs e)
{
resultsTextBox.Clear();
await CreateMultipleTasksAsync();
resultsTextBox.Text += "\r\n\r\nControl returned to startButton_Click.\r\n";
}
private async Task CreateMultipleTasksAsync()
{
// Declare an HttpClient object, and increase the buffer size. The
// default buffer size is 65,536.
HttpClient client =
new HttpClient() { MaxResponseContentBufferSize = 1000000 };
// Create and start the tasks. As each task finishes, DisplayResults
// displays its length.
Task<int> download1 =
ProcessURLAsync("https://msdn.microsoft.com", client);
Task<int> download2 =
ProcessURLAsync("https://msdn.microsoft.com/en-us/library/hh156528(VS.110).aspx", client);
Task<int> download3 =
ProcessURLAsync("https://msdn.microsoft.com/en-us/library/67w7t67f.aspx", client);
// Await each task.
int length1 = await download1;
int length2 = await download2;
int length3 = await download3;
int total = length1 + length2 + length3;
// Display the total count for the downloaded websites.
resultsTextBox.Text +=
string.Format("\r\n\r\nTotal bytes returned: {0}\r\n", total);
}
async Task<int> ProcessURLAsync(string url, HttpClient client)
{
var byteArray = await client.GetByteArrayAsync(url);
DisplayResults(url, byteArray);
return byteArray.Length;
}
private void DisplayResults(string url, byte[] content)
{
// 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.
var bytes = content.Length;
// Strip off the "http://".
var displayURL = url.Replace("http://", "");
resultsTextBox.Text += string.Format("\n{0,-58} {1,8}", displayURL, bytes);
}
}
}
Vedere anche
Attività
Procedura dettagliata: accesso al Web tramite Async e Await (C# e Visual Basic)
Procedura: estendere la procedura dettagliata tramite Task.WhenAll (C# e Visual Basic)
Concetti
Programmazione asincrona con Async e Await (C# e Visual Basic)