Aracılığıyla paylaş


Nasıl yapılır: birden çok Web isteği paralel (C# ve Visual Basic) yapmak

Oluşturuldukları zaman zaman uyumsuz yöntem görevleri başlatılır.Await (Visual Basic) ya da beklemek (C#) işleci görev noktasında burada işleme devam edemiyor görev bitene kadar yöntemi uygulanır.Genellikle, aşağıdaki örnekte gösterildiği gibi oluşturulduktan hemen sonra görevi beklediğin.

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

Ancak, görevin tamamlanma bağımlı değildir gerçekleştirmek için diğer iş programınız varsa, görev bekleyen gelen görev oluşturma ayırabilirsiniz.

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

Bir görevi başlatmak ve onu bekleyen arasında diğer görevleri başlatabilirsiniz.Ek görevler örtülü olarak paralel olarak çalışır, ancak ek iş parçacığı oluşturulur.

Aşağıdaki programı üç zaman uyumsuz web yüklemeleri başlar ve onları adlı sırada bekler.Bildirimin görevler her zaman içinde bunlar oluşturulan beklediğin ve sırada son verme programı çalıştırdığınızda.Oluşturuldukları ve yöntem await ifadeler ulaşmadan önce bir veya daha fazla görev bitiş çalışmaya başlayın.

Aynı anda birden çok görevi başlatan başka bir örnek için bkz: Nasıl yapılır: Task.WhenAll (C# ve Visual Basic) kullanarak izlenecek yol genişletme.

Bu projeyi tamamlamak için bilgisayarınızda olması Visual Studio 2012 bilgisayarınızda yüklü.Daha fazla bilgi için bkz: Microsoft Web sitesini ziyaret.

Bu örneğin kodu yükleyebilirsiniz Developer kod örnekleri.

Proje ayarlamak için

Kod eklemek için

  1. Tasarım penceresinde, MainWindow.xaml, oluşturmak için düğmeyi çift startButton_Click MainWindow.xaml.vb ya da MainWindow.xaml.cs olay işleyicisi.Alternatif olarak, düğmeyi seçin, Seç Seçili öğeler için olay işleyicileri simgesi özellikleri penceresinde yazıp enter startButton_Click , 'I metin kutusu.

  2. Aşağıdaki kodu kopyalayın ve gövdesine yapıştırın startButton_Click MainWindow.xaml.vb ya da 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 bir zaman uyumsuz yöntemini çağırır CreateMultipleTasksAsync, uygulama sürücüler.

  3. Aşağıdaki destek yöntemleri projeye ekleyin:

    • ProcessURLAsynckullanan bir HttpClient bir bayt dizisi olarak bir Web sitesi içeriğini karşıdan yüklemek için yöntem.Destek yöntemi ProcessURLAsync sonra görüntüler ve dizi uzunluğu döndürür.

    • DisplayResultsbayt bayt dizisi, her url için görüntüler.Bu görüntüler gösterir her görev karşıdan yüklemeyi tamamladığında.

    Aşağıdaki yöntemlerden kopyalayın ve sonra kopyalayıp yapıştırdığımda startButton_Click MainWindow.xaml.vb ya da MainWindow.xaml.cs olay işleyicisi.

    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. Son olarak, yöntem tanımlamak CreateMultipleTasksAsync, aşağıdaki adımları gerçekleştirir.

    • Yöntemi bildirir bir HttpClient yöntemi erişmeniz gereken nesnenin GetByteArrayAsync , ProcessURLAsync.

    • Yöntemi oluşturur ve başlatır üç görev türü Task<TResult>, burada TResult bir tamsayıdır.Her görev tamamlandıktan gibi DisplayResults görevin URL'si ve karşıdan yüklenen içeriğinin uzunluğu görüntüler.Görevleri zaman uyumsuz olarak çalıştığından, sonuçların görüntülenme sırasını bildirilmiş siparişten farklılık gösterebilir.

    • Yöntem, her görevin tamamlanmasını bekler.Her Await veya await operator yürütülmesini askıya CreateMultipleTasksAsync awaited görev bitene kadar.Operatör çağrısı dönüş değeri de alır ProcessURLAsync tamamlanan her görevden.

    • Tamsayı değerleri alınır ve görevler tamamlandığında, yöntem Web sitelerinin uzunlukları toplamlarını hesaplar ve sonucu görüntüler.

    Aşağıdaki yöntem kopyalayın ve çözümünüzün yapıştırın.

    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. Seçim programını çalıştırın ve sonra seçmek için F5 tuşuna Start düğme.

    Üç görevi her zaman aynı sırada son verme ve içinde son sipariş mutlaka içinde bunlar oluşturulan beklediğin ve sipariş değil doğrulamak için birkaç kez programı çalıştırın.

Örnek

Aşağıdaki kod, tam örnek içerir.

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

Ayrıca bkz.

Görevler

İzlenecek yol: zaman uyumsuz kullanarak Web'e erişme ve (C# ve Visual Basic) beklemek

Nasıl yapılır: Task.WhenAll (C# ve Visual Basic) kullanarak izlenecek yol genişletme

Kavramlar

Zaman uyumsuz zaman uyumsuz programlama ve beklemek (C# ve Visual Basic)