Udostępnij za pośrednictwem


Jak: tworzenie wielu sieci Web żądania równolegle (C# i Visual Basic)

Metody asynchronicznej zadania są uruchamiane, gdy są one tworzone.Await (Visual Basic) lub czekają na (C#) operator jest stosowany do zadań w punkcie w metodzie, których przetwarzanie nie może kontynuować przed zakończeniem zadania.Często zadania jest oczekiwana natychmiast po jego utworzeniu, jak pokazano w następującym przykładzie.

Dim result = Await someWebAccessMethodAsync(url)
var result = await someWebAccessMethodAsync(url);

Jednakże można oddzielić tworzenia zadania z Oczekujące na zadanie, jeśli program ma wykonać inne działania, które nie zależą od zakończenia zadania.

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

Między uruchamianie zadania i oczekuje ona, można uruchomić inne zadania.Dodatkowe zadania niejawnie równolegle, ale żadne dodatkowe wątki są tworzone.

Następujący program uruchamia trzy web asynchronicznego pobrania i oczekuje je w kolejności, w której są nazywane.Zawiadomienie, po uruchomieniu programu, zakończenia zadań nie zawsze w kolejności, w której są tworzone i oczekiwane.Uruchamiają uruchomić, gdy są one tworzone i jeden lub więcej zadań może zakończyć się przed metoda osiąga wyrażeń await.

Inny przykład uruchamia jednocześnie wiele zadań, zobacz Jak: rozszerzenie Instruktaż przy użyciu Task.WhenAll (C# i Visual Basic).

Aby ukończyć tego projektu, musi mieć Visual Studio 2012 zainstalowane na komputerze.Aby uzyskać więcej informacji, zobacz witryny sieci Web Microsoft.

Można pobrać kodu tego przykładu z Developer przykłady kodu.

Aby skonfigurować projektu

Aby dodać kod

  1. W oknie projektu, MainWindow.xaml, kliknij dwukrotnie przycisk, aby utworzyć startButton_Click obsługi zdarzeń w MainWindow.xaml.vb lub MainWindow.xaml.cs.Jako alternatywę, wybierz przycisk, zaznacz obsługi zdarzeń dla wybranych elementów ikonę w Właściwości okno, a następnie wprowadź startButton_Click w kliknij pole tekstowe.

  2. Skopiuj poniższy kod i wklej go do treści startButton_Click w MainWindow.xaml.vb lub 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";
    

    Kod wywołuje metodę asynchronicznych CreateMultipleTasksAsync, które dyski aplikacji.

  3. Dodaj następujące metody pomocy technicznej do projektu:

    • ProcessURLAsyncużywa HttpClient metoda pobierania zawartości internetowej jako tablicy bajtów.Metoda obsługi ProcessURLAsync następnie wyświetla i zwraca długość tablicy.

    • DisplayResultsWyświetla liczbę bajtów w tablicy bajtowej dla każdego adresu URL.Wyświetlanie pokazuje, po zakończeniu pobierania poszczególnych zadań.

    Następujące metody skopiować i wkleić je po startButton_Click obsługi zdarzeń w MainWindow.xaml.vb lub 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);
    }
    
  4. Wreszcie, należy zdefiniować metodę CreateMultipleTasksAsync, który wykonuje następujące kroki.

    • Deklaruje metody HttpClient obiekt, który chce korzystać z metody GetByteArrayAsync w ProcessURLAsync.

    • Metoda tworzy i uruchamia trzy zadania typu Task<TResult>, gdzie TResult jest liczbą całkowitą.Zakończeniu każdego zadania, DisplayResults Wyświetla adres URL zadania i długość pobrane zawartości.Ponieważ zadania działają asynchronicznie, kolejność wyświetlania wyników mogą różnić się od zamówienia, w której zostały zadeklarowane.

    • Metoda oczekuje zakończenia każdego zadania.Każdy Await lub await operator wstrzymuje wykonywanie CreateMultipleTasksAsync do momentu zakończenia zadań oczekiwany.Operator również pobiera wartość zwracana z wywołanie ProcessURLAsync z każdego zadania ukończone.

    • Po zakończeniu zadania i pobrano wartości całkowite, metoda sumuje długość witryn sieci Web i wyświetla wynik.

    Skopiuj następujące metody i wkleić go do rozwiązania.

    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);
    }
    
  5. Wybierz klawisz F5, aby uruchomić program, a następnie wybierz Start przycisku.

    Uruchom program kilka razy, aby zweryfikować, że trzy zadania zawsze nie zakończy się w tej samej kolejności i że kolejność ich zakończenia niekoniecznie kolejność, w której są tworzone i oczekiwane.

Przykład

Poniższy kod zawiera pełny przykład.

' 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);
        }
    }
}

Zobacz też

Zadania

Instruktaż: Dostęp do sieci Web za pomocą transmisji asynchronicznej i poczekać (C# i Visual Basic)

Jak: rozszerzenie Instruktaż przy użyciu Task.WhenAll (C# i Visual Basic)

Koncepcje

Asynchroniczne programowania przy użyciu asynchronicznej i poczekać (C# i Visual Basic)