Aracılığıyla paylaş


Zaman Uyumsuz Uygulamalarda Yeniden Girişi İşleme (C# ve Visual Basic)

Sizin app içinde zaman uyumsuz kod eklediğinizde, göz önünde bulundurun ve büyük olasılıkla yeniden giriş zaman uyumsuz işlemi tamamlandıktan önce Project'e için başvuran önlemek gerekir.Tanımlamak ve yeniden giriş olasılıklarını ele değilseniz, beklenmedik sonuçlara neden olabilir.

Bu konuda

[!NOT]

' Ndaki yönergeleri İnceleme ve örnek uygulama çalıştırma Windows Presentation Foundation (wpf) uygulaması veya Windows Store app olarak kodu çalıştırmak için nasıl gösterir.

Örnek bir wpf uygulama çalıştırmak için Visual Studio 2012 sahip Visual Studio Express 2012 için Windows Masaüstü, veya bilgisayarınızda yüklü .NET Framework 4.5.

Örnek olarak çalıştırmak için bir Windows Mağazası app, Windows 8 bilgisayarınızda yüklü olması gerekir.Ayrıca, bu örnek Visual Studio'dan çalıştırmak istiyorsanız, Visual Studio 2012 de olmalıdır veya Visual Studio Express 2012 Windows 8 yüklü.

Yeniden giriş tanıma

Bu konudaki örnek, kullanıcıların seçim bir Start Web sitelerine bir dizi yüklemeleri ve karşıdan yüklenen bayt toplam sayısını hesaplar zaman uyumsuz bir uygulama başlatmak için düğme.Örnek zaman uyumlu bir sürümü aynı şekilde bakılmaksızın ilk oynamadan sonra UI iş parçacığı uygulama çalýþmayý kadar olaylarını yoksayar çünkü kaç kez bir kullanıcı düğmeyi seçer. yanıt.Zaman uyumsuz bir uygulama ancak, UI iş parçacığı yanıt devam eder ve zaman uyumsuz işlem tamamlandı, önce yeniden.

Aşağıdaki örnek, beklenen gösterir kullanıcı seçtiğinde çıktı Başlat düğmesi yalnızca bir kez.Her site bayt cinsinden boyutu karşıdan yüklenen Web sitelerinin bir listesi görüntülenir.Toplam bayt sayısı sonunda görünür.

1. msdn.microsoft.com/en-us/library/hh191443.aspx                83732
2. msdn.microsoft.com/en-us/library/aa578028.aspx               205273
3. msdn.microsoft.com/en-us/library/jj155761.aspx                29019
4. msdn.microsoft.com/en-us/library/hh290140.aspx               117152
5. msdn.microsoft.com/en-us/library/hh524395.aspx                68959
6. msdn.microsoft.com/en-us/library/ms404677.aspx               197325
7. msdn.microsoft.com                                            42972
8. msdn.microsoft.com/en-us/library/ff730837.aspx               146159

TOTAL bytes returned:  890591

Ancak, kullanıcının birden çok kez düğmesini seçerse, sürekli olarak olay işleyicisi çağrılır ve karşıdan yükleme işlemi her zaman reentered.Sonuç olarak, aynı anda birden çok zaman uyumsuz işlemler çalıştırıyorsanız, sonuçları çıktı interleaves ve kafa karıştırıcı toplam bayt sayısı.

1. msdn.microsoft.com/en-us/library/hh191443.aspx                83732
2. msdn.microsoft.com/en-us/library/aa578028.aspx               205273
3. msdn.microsoft.com/en-us/library/jj155761.aspx                29019
4. msdn.microsoft.com/en-us/library/hh290140.aspx               117152
5. msdn.microsoft.com/en-us/library/hh524395.aspx                68959
1. msdn.microsoft.com/en-us/library/hh191443.aspx                83732
2. msdn.microsoft.com/en-us/library/aa578028.aspx               205273
6. msdn.microsoft.com/en-us/library/ms404677.aspx               197325
3. msdn.microsoft.com/en-us/library/jj155761.aspx                29019
7. msdn.microsoft.com                                            42972
4. msdn.microsoft.com/en-us/library/hh290140.aspx               117152
8. msdn.microsoft.com/en-us/library/ff730837.aspx               146159

TOTAL bytes returned:  890591

5. msdn.microsoft.com/en-us/library/hh524395.aspx                68959
1. msdn.microsoft.com/en-us/library/hh191443.aspx                83732
2. msdn.microsoft.com/en-us/library/aa578028.aspx               205273
6. msdn.microsoft.com/en-us/library/ms404677.aspx               197325
3. msdn.microsoft.com/en-us/library/jj155761.aspx                29019
4. msdn.microsoft.com/en-us/library/hh290140.aspx               117152
7. msdn.microsoft.com                                            42972
5. msdn.microsoft.com/en-us/library/hh524395.aspx                68959
8. msdn.microsoft.com/en-us/library/ff730837.aspx               146159

TOTAL bytes returned:  890591

6. msdn.microsoft.com/en-us/library/ms404677.aspx               197325
7. msdn.microsoft.com                                            42972
8. msdn.microsoft.com/en-us/library/ff730837.aspx               146159

TOTAL bytes returned:  890591

Bu konuda sonuna kaydırma yaparak bu çıktıyı üretir kod gözden geçirebilirsiniz.Kodu çözüm yerel bilgisayarınıza yüklemek ve WebsiteDownload projeyi çalıştırmayı deneyebilirsiniz veya daha fazla bilgi ve yönergeler kendi projesi oluşturmak için bu konunun sonunda kodu kullanarak tarafından bkz: İnceleme ve örnek uygulama çalıştırma.

Yeniden işleme giriş

Yeniden giriş yolları, app yapmak istediğinize bağlı olarak, çeşitli işleyebilir.Bu konu Aşağıdaki örnekler sunar:

JJ651641.collapse_all(tr-tr,VS.110).gifBaşlat düğmesini devre dışı bırak

Bloke edebilirsiniz Start bir işlem en üstündeki düğmeyi devre dışı bırakarak çalışırken düğmesini StartButton_Click olay işleyicisi.İçinden düğmesini sonra etkinleştirebileceğiniz bir finally engellemek kullanıcıların app yeniden çalıştırabilmeniz için işlemi bittikten sonra.

Aşağıdaki kod bu değişiklikler, yıldız işareti ile işaretlenmiş gösterir.Bu konunun sonundaki kodda değişiklikler ekleyebilir veya tamamlanmış app indirebilirsiniz zaman uyumsuz örnekleri: .NET Masaüstü Apps içinde yeniden giriş veya zaman uyumsuz örnekleri: Windows mağaza Apps içinde yeniden giriş.Projenin adı DisableStartButton'dır.

Private Async Sub StartButton_Click(sender As Object, e As RoutedEventArgs)
    ' This line is commented out to make the results clearer in the output.
    'ResultsTextBox.Text = ""

    ' ***Disable the Start button until the downloads are complete. 
    StartButton.IsEnabled = False

    Try
        Await AccessTheWebAsync()

    Catch ex As Exception
        ResultsTextBox.Text &= vbCrLf & "Downloads failed."
    ' ***Enable the Start button in case you want to run the program again. 
    Finally
        StartButton.IsEnabled = True

    End Try
End Sub
private async void StartButton_Click(object sender, RoutedEventArgs e)
{
    // This line is commented out to make the results clearer in the output.
    //ResultsTextBox.Text = "";

    // ***Disable the Start button until the downloads are complete. 
    StartButton.IsEnabled = false; 

    try
    {
        await AccessTheWebAsync();
    }
    catch (Exception)
    {
        ResultsTextBox.Text += "\r\nDownloads failed.";
    }
    // ***Enable the Start button in case you want to run the program again. 
    finally
    {
        StartButton.IsEnabled = true;
    }
}

Değişikliklerin sonucu olarak, düğme yanıt vermez iken AccessTheWebAsync Web sitelerinin işlem reentered şekilde karşıdan yüklüyor.

JJ651641.collapse_all(tr-tr,VS.110).gifİptal etmek ve işlemi yeniden başlatın

Devre dışı bırakmak yerine Start düğmesini kullanabilirsiniz düğmesi etkin tutmak ancak, kullanıcı bu düğmeyi yeniden seçerse, zaten çalışıyor ve son zamanlarda başlatılan işlemin devam etmesine izin vermek işlemi iptal etmek.

İptal etme hakkında daha fazla bilgi için bkz: İnce ayar zaman uyumsuz uygulamanız.

Bu senaryo için sağlanan temel kod aşağıdaki değişiklikleri yapın İnceleme ve örnek uygulama çalıştırma.Tamamlanmış app karşıdan yükleyebileceğiniz zaman uyumsuz örnekleri: .NET Masaüstü Apps içinde yeniden giriş veya zaman uyumsuz örnekleri: Windows mağaza Apps içinde yeniden giriş.Bu proje CancelAndRestart adıdır.

  1. Bildirdiğiniz bir CancellationTokenSource değişkeni, cts, tüm yöntemleri kapsamı içinde olan.

    Class MainWindow // Or Class MainPage
    
        ' *** Declare a System.Threading.CancellationTokenSource.
        Dim cts As CancellationTokenSource
    
    public partial class MainWindow : Window   // Or class MainPage
    {
        // *** Declare a System.Threading.CancellationTokenSource.
        CancellationTokenSource cts;
    
  2. İçinde StartButton_Click, bir işlem zaten çalışma halindeyken olup olmadığını belirlemek.Değeri cts null (Nothing Visual Basic), hiçbir işlemi etkin durumda.Değer null değilse, çalışmakta olan işlem iptal edildi.

    ' *** If a download process is already underway, cancel it.
    If cts IsNot Nothing Then
        cts.Cancel()
    End If
    
    // *** If a download process is already underway, cancel it.
    if (cts != null)
    {
        cts.Cancel();
    }
    
  3. Set cts farklı bir değere geçerli işlemi temsil eder.

    ' *** Now set cts to cancel the current process if the button is chosen again.
    Dim newCTS As CancellationTokenSource = New CancellationTokenSource()
    cts = newCTS
    
    // *** Now set cts to a new value that you can use to cancel the current process
    // if the button is chosen again.
    CancellationTokenSource newCTS = new CancellationTokenSource();
    cts = newCTS;
    
  4. Sonunda, StartButton_Click, geçerli işlemi tamamlandığında, bu nedenle değerini cts null dön.

    ' *** When the process completes, signal that another process can proceed.
    If cts Is newCTS Then
        cts = Nothing
    End If
    
    // *** When the process is complete, signal that another process can begin.
    if (cts == newCTS)
        cts = null;
    

Aşağıdaki kod, tüm değişiklikleri gösterir StartButton_Click.Eklemeler, yıldız işareti ile işaretlenir.

Private Async Sub StartButton_Click(sender As Object, e As RoutedEventArgs)

    ' This line is commented out to make the results clearer. 
    'ResultsTextBox.Text = ""


    ' *** If a download process is underway, cancel it.
    If cts IsNot Nothing Then
        cts.Cancel()
    End If

    ' *** Now set cts to cancel the current process if the button is chosen again.
    Dim newCTS As CancellationTokenSource = New CancellationTokenSource()
    cts = newCTS

    Try
        ' *** Send a token to carry the message if the operation is canceled.
        Await AccessTheWebAsync(cts.Token)
        

    Catch ex As OperationCanceledException
        ResultsTextBox.Text &= vbCrLf & "Download canceled." & vbCrLf

    Catch ex As Exception
        ResultsTextBox.Text &= vbCrLf & "Downloads failed."
    End Try

    ' *** When the process is complete, signal that another process can proceed.
    If cts Is newCTS Then
        cts = Nothing
    End If
End Sub
private async void StartButton_Click(object sender, RoutedEventArgs e)
{
    // This line is commented out to make the results clearer in the output.
    //ResultsTextBox.Clear();

    // *** If a download process is already underway, cancel it.
    if (cts != null)
    {
        cts.Cancel();
    }

    // *** Now set cts to cancel the current process if the button is chosen again.
    CancellationTokenSource newCTS = new CancellationTokenSource();
    cts = newCTS;

    try
    {
        // ***Send cts.Token to carry the message if there is a cancellation request.
        await AccessTheWebAsync(cts.Token);
        
    }
    // *** Catch cancellations separately.
    catch (OperationCanceledException)
    {
        ResultsTextBox.Text += "\r\nDownloads canceled.\r\n";
    }
    catch (Exception)
    {
        ResultsTextBox.Text += "\r\nDownloads failed.\r\n";
    }
    // *** When the process is complete, signal that another process can proceed.
    if (cts == newCTS)
        cts = null;
}

İçinde AccessTheWebAsync, aşağıdaki değişiklikleri yapın.

  • İptali belirteci kabul etmek için parametre ekleme StartButton_Click.

  • Kullanım GetAsync Web siteleri için karşıdan yükleme yöntemi GetAsync kabul eden bir CancellationToken bağımsız değişkeni.

  • Çağırmadan önce DisplayResults yüklenen her Web sitesi için sonuçları görüntülemek için kontrol ct için geçerli işlem iptal taşınmadığından emin olun.

Aşağıdaki kod bu değişiklikler, yıldız işareti ile işaretlenmiş gösterir.

' *** Provide a parameter for the CancellationToken from StartButton_Click.
Private Async Function AccessTheWebAsync(ct As CancellationToken) As Task

    ' Declare an HttpClient object.
    Dim client = New HttpClient()

    ' Make a list of web addresses.
    Dim urlList As List(Of String) = SetUpURLList()

    Dim total = 0
    Dim position = 0

    For Each url In urlList
        ' *** Use the HttpClient.GetAsync method because it accepts a 
        ' cancellation token.
        Dim response As HttpResponseMessage = Await client.GetAsync(url, ct)

        ' *** Retrieve the website contents from the HttpResponseMessage.
        Dim urlContents As Byte() = Await response.Content.ReadAsByteArrayAsync()

        ' *** Check for cancellations before displaying information about the 
        ' latest site. 
        ct.ThrowIfCancellationRequested()

        position += 1
        DisplayResults(url, urlContents, position)

        ' Update the total.
        total += urlContents.Length
    Next

    ' Display the total count for all of the websites.
    ResultsTextBox.Text &=
        String.Format(vbCrLf & vbCrLf & "TOTAL bytes returned:  " & total & vbCrLf)
End Function
// *** Provide a parameter for the CancellationToken from StartButton_Click.
async Task AccessTheWebAsync(CancellationToken ct)
{
    // Declare an HttpClient object.
    HttpClient client = new HttpClient();

    // Make a list of web addresses.
    List<string> urlList = SetUpURLList();

    var total = 0;
    var position = 0;

    foreach (var url in urlList)
    {
        // *** Use the HttpClient.GetAsync method because it accepts a 
        // cancellation token.
        HttpResponseMessage response = await client.GetAsync(url, ct);

        // *** Retrieve the website contents from the HttpResponseMessage.
        byte[] urlContents = await response.Content.ReadAsByteArrayAsync();

        // *** Check for cancellations before displaying information about the 
        // latest site. 
        ct.ThrowIfCancellationRequested();

        DisplayResults(url, urlContents, ++position);

        // Update the total.
        total += urlContents.Length;
    }

    // Display the total count for all of the websites.
    ResultsTextBox.Text +=
        string.Format("\r\n\r\nTOTAL bytes returned:  {0}\r\n", total);
}   

İsterseniz Start düğmesini birkaç kez bu uygulama çalışırken aşağıdaki çıktıyı benzer sonuçlar üretir.

1. msdn.microsoft.com/en-us/library/hh191443.aspx                83732
2. msdn.microsoft.com/en-us/library/aa578028.aspx               205273
3. msdn.microsoft.com/en-us/library/jj155761.aspx                29019
4. msdn.microsoft.com/en-us/library/hh290140.aspx               122505
5. msdn.microsoft.com/en-us/library/hh524395.aspx                68959
6. msdn.microsoft.com/en-us/library/ms404677.aspx               197325
Download canceled.

1. msdn.microsoft.com/en-us/library/hh191443.aspx                83732
2. msdn.microsoft.com/en-us/library/aa578028.aspx               205273
3. msdn.microsoft.com/en-us/library/jj155761.aspx                29019
Download canceled.

1. msdn.microsoft.com/en-us/library/hh191443.aspx                83732
2. msdn.microsoft.com/en-us/library/aa578028.aspx               205273
3. msdn.microsoft.com/en-us/library/jj155761.aspx                29019
4. msdn.microsoft.com/en-us/library/hh290140.aspx               117152
5. msdn.microsoft.com/en-us/library/hh524395.aspx                68959
6. msdn.microsoft.com/en-us/library/ms404677.aspx               197325
7. msdn.microsoft.com                                            42972
8. msdn.microsoft.com/en-us/library/ff730837.aspx               146159

TOTAL bytes returned:  890591

Kısmi listelerini ortadan kaldırmak için kod ilk satırı yorumsuz StartButton_Click kullanıcı işlemi yeniden her zaman metin kutusunu temizleyin.

JJ651641.collapse_all(tr-tr,VS.110).gifBirden çok işlemi çalıştırmak ve sıraya çıktı

Başka bir zaman uyumsuz işlem kullanıcı her zaman uygulama başlar, bu üçüncü örnek en karmaşık olan Başlat düğme ve tüm işlemlerin tamamlanması için çalıştırın.Karşıdan istenen tüm işlemleri Web siteleri listesinden zaman uyumsuz olarak yükle, ancak operasyonlar çıktısını ardışık olarak sunulur.Diğer bir deyişle, gerçek yükleme etkinliği, çıkış olarak Aralanmış Yeniden giriş tanıma gösterir, ancak her grup için sonuçlar listesi sunulur ayrı ayrı.

Genel bir işlem paylaşmak Task, pendingWork, görüntü işlemi için bir ağ geçidi denetleyicisi olarak sunar.

Kodun içine girmek değişiklikleri yapıştırarak bu örneği çalıştırmak Uygulama oluşturma, ya da yer alan yönergeleri takip edebilirsiniz Uygulama yükleme örnek sonra QueueResults projeyi çalıştırmayı dener.

Kullanıcı seçtiğinde sonucu aşağıdaki çıktıyı göstermektedir Start yalnızca bir kez düğme.a, mektup etiketi, sonuç ilk kez olduğunu gösteren Başlat düğmesi seçilmişse.Sayıları yükleme hedefler listesinde URL'lerin sırasını gösterir.

#Starting group A.
#Task assigned for group A.

A-1. msdn.microsoft.com/en-us/library/hh191443.aspx                87389
A-2. msdn.microsoft.com/en-us/library/aa578028.aspx               209858
A-3. msdn.microsoft.com/en-us/library/jj155761.aspx                30870
A-4. msdn.microsoft.com/en-us/library/hh290140.aspx               119027
A-5. msdn.microsoft.com/en-us/library/hh524395.aspx                71260
A-6. msdn.microsoft.com/en-us/library/ms404677.aspx               199186
A-7. msdn.microsoft.com                                            53266
A-8. msdn.microsoft.com/en-us/library/ff730837.aspx               148020

TOTAL bytes returned:  918876


#Group A is complete.

Kullanıcı seçerse, Start düğmesini üç kez, uygulama aşağıdaki satırları benzer bir çıktı üretir.Bir pound ile başlayan bilgi satırları (#) izleme ilerleme uygulamanın oturum açın.

#Starting group A.
#Task assigned for group A.

A-1. msdn.microsoft.com/en-us/library/hh191443.aspx                87389
A-2. msdn.microsoft.com/en-us/library/aa578028.aspx               207089
A-3. msdn.microsoft.com/en-us/library/jj155761.aspx                30870
A-4. msdn.microsoft.com/en-us/library/hh290140.aspx               119027
A-5. msdn.microsoft.com/en-us/library/hh524395.aspx                71259
A-6. msdn.microsoft.com/en-us/library/ms404677.aspx               199185

#Starting group B.
#Task assigned for group B.

A-7. msdn.microsoft.com                                            53266

#Starting group C.
#Task assigned for group C.

A-8. msdn.microsoft.com/en-us/library/ff730837.aspx               148010

TOTAL bytes returned:  916095

B-1. msdn.microsoft.com/en-us/library/hh191443.aspx                87389
B-2. msdn.microsoft.com/en-us/library/aa578028.aspx               207089
B-3. msdn.microsoft.com/en-us/library/jj155761.aspx                30870
B-4. msdn.microsoft.com/en-us/library/hh290140.aspx               119027
B-5. msdn.microsoft.com/en-us/library/hh524395.aspx                71260
B-6. msdn.microsoft.com/en-us/library/ms404677.aspx               199186

#Group A is complete.

B-7. msdn.microsoft.com                                            53266
B-8. msdn.microsoft.com/en-us/library/ff730837.aspx               148010

TOTAL bytes returned:  916097

C-1. msdn.microsoft.com/en-us/library/hh191443.aspx                87389
C-2. msdn.microsoft.com/en-us/library/aa578028.aspx               207089

#Group B is complete.

C-3. msdn.microsoft.com/en-us/library/jj155761.aspx                30870
C-4. msdn.microsoft.com/en-us/library/hh290140.aspx               119027
C-5. msdn.microsoft.com/en-us/library/hh524395.aspx                72765
C-6. msdn.microsoft.com/en-us/library/ms404677.aspx               199186
C-7. msdn.microsoft.com                                            56190
C-8. msdn.microsoft.com/en-us/library/ff730837.aspx               148010

TOTAL bytes returned:  920526

#Group C is complete.

b ve c grupları Grup a tamamladı, ancak çıktıyı her grup için ayrı ayrı görüntülenir önce başlatın.Ardından b grubu için tüm çıkış ve sonra tüm çıktı c grubu için Grup a tüm çıktı ilk olarak görüntülenirUygulama her zaman grupları sırayla görüntüler ve her grup için URL'leri URL'leri listede sırayla her zaman tek tek Web siteleri hakkında bilgileri görüntüler.

Ancak, karşıdan yüklemeler gerçekte durum ortaya sipariş tahmin edemezsiniz.Birden fazla grup başlattıktan sonra oluşturdukları yükleme tüm etkin görevlerdir.Bu a-1 varsayamazsınız önce b-1 karşıdan yüklenir ve bu a-1 varsayamazsınız a-2 önce yüklenir.

JJ651641.collapse_all(tr-tr,VS.110).gifGenel tanımları

Örnek kod, tüm yöntemleri görünen aşağıdaki iki genel bildirimleri içerir.

Class MainWindow    ' Class MainPage in Windows Store app.

    ' ***Declare the following variables where all methods can access them. 
    Private pendingWork As Task = Nothing
    Private group As Char = ChrW(AscW("A") - 1)
public partial class MainWindow : Window  // Class MainPage in Windows Store app.
{
    // ***Declare the following variables where all methods can access them. 
    private Task pendingWork = null;   
    private char group = (char)('A' - 1);

Task Değişkeni, pendingWork, görüntü işleme gelişimini denetler ve herhangi bir grubu başka bir grubun görüntüleme işlemini önler.Karakter değişkeni group, etiketler çıktı farklı gruplardan sonuçları beklenen sırayla görüntülendiğinden emin olun.

JJ651641.collapse_all(tr-tr,VS.110).gifClick olay işleyicisi

Olay işleyicisi StartButton_Click, kullanıcının seçtiği her defasında grup harf artırır Start düğmesi.Sonra işleyicisi çağrılarını AccessTheWebAsync karşıdan yükleme işlemi çalıştırmak için.

Private Async Sub StartButton_Click(sender As Object, e As RoutedEventArgs)
    ' ***Verify that each group's results are displayed together, and that
    ' the groups display in order, by marking each group with a letter.
    group = ChrW(AscW(group) + 1)
    ResultsTextBox.Text &= String.Format(vbCrLf & vbCrLf & "#Starting group {0}.", group)

    Try
        ' *** Pass the group value to AccessTheWebAsync.
        Dim finishedGroup As Char = Await AccessTheWebAsync(group)

        ' The following line verifies a successful return from the download and 
        ' display procedures. 
        ResultsTextBox.Text &= String.Format(vbCrLf & vbCrLf & "#Group {0} is complete." & vbCrLf, finishedGroup)

    Catch ex As Exception
        ResultsTextBox.Text &= vbCrLf & "Downloads failed."

    End Try
End Sub
private async void StartButton_Click(object sender, RoutedEventArgs e)
{
    // ***Verify that each group's results are displayed together, and that
    // the groups display in order, by marking each group with a letter.
    group = (char)(group + 1);
    ResultsTextBox.Text += string.Format("\r\n\r\n#Starting group {0}.", group);

    try
    {
        // *** Pass the group value to AccessTheWebAsync.
        char finishedGroup = await AccessTheWebAsync(group);

        // The following line verifies a successful return from the download and
        // display procedures. 
        ResultsTextBox.Text += string.Format("\r\n\r\n#Group {0} is complete.\r\n", finishedGroup);
    }
    catch (Exception)
    {
        ResultsTextBox.Text += "\r\nDownloads failed.";
    }
}

JJ651641.collapse_all(tr-tr,VS.110).gifAccessTheWebAsync yöntemi

Bu örnek böler AccessTheWebAsync iki yöntem içine.İlk yöntem, AccessTheWebAsync, bir grup için tüm yükleme görevleri başlatır ve kurar pendingWork görüntü işlemini kontrol eden.Dil ile tümleşik sorgu (LINQ sorgusu) yöntemini kullanır ve ToArray<TSource> aynı anda yükleme görevleri başlatmak için.

AccessTheWebAsyncDaha sonra FinishOneGroupAsync her karşıdan yükleme tamamlanmasını bekler ve uzunluğunu görüntüler.

FinishOneGroupAsyncatanan bir görev verir pendingWork , AccessTheWebAsync.Görev tamamlanmadan önce değer kesinti başka bir işlem tarafından engel olduğunu.

Private Async Function AccessTheWebAsync(grp As Char) As Task(Of Char)

    Dim client = New HttpClient()

    ' Make a list of the web addresses to download.
    Dim urlList As List(Of String) = SetUpURLList()

    ' ***Kick off the downloads. The application of ToArray activates all the download tasks.
    Dim getContentTasks As Task(Of Byte())() =
        urlList.Select(Function(addr) client.GetByteArrayAsync(addr)).ToArray()

    ' ***Call the method that awaits the downloads and displays the results.
    ' Assign the Task that FinishOneGroupAsync returns to the gatekeeper task, pendingWork.
    pendingWork = FinishOneGroupAsync(urlList, getContentTasks, grp)

    ResultsTextBox.Text &=
        String.Format(vbCrLf & "#Task assigned for group {0}. Download tasks are active." & vbCrLf, grp)

    ' ***This task is complete when a group has finished downloading and displaying.
    Await pendingWork

    ' You can do other work here or just return.
    Return grp
End Function
private async Task<char> AccessTheWebAsync(char grp)
{
    HttpClient client = new HttpClient();

    // Make a list of the web addresses to download.
    List<string> urlList = SetUpURLList();

    // ***Kick off the downloads. The application of ToArray activates all the download tasks.
    Task<byte[]>[] getContentTasks = urlList.Select(url => client.GetByteArrayAsync(url)).ToArray();

    // ***Call the method that awaits the downloads and displays the results.
    // Assign the Task that FinishOneGroupAsync returns to the gatekeeper task, pendingWork.
    pendingWork = FinishOneGroupAsync(urlList, getContentTasks, grp);

    ResultsTextBox.Text += string.Format("\r\n#Task assigned for group {0}. Download tasks are active.\r\n", grp);

    // ***This task is complete when a group has finished downloading and displaying.
    await pendingWork;

    // You can do other work here or just return.
    return grp;
}

JJ651641.collapse_all(tr-tr,VS.110).gifFinishOneGroupAsync yöntemi

Bu yöntem, her biri bekleniyor, karşıdan yüklenen Web sitesi uzunluğunu görüntüleme ve uzunluğu için toplam ekleme bir grup halinde yükleme görevleri aracılığıyla döngüleri.

İlk ifade, FinishOneGroupAsync kullanan pendingWork girme yöntemi zaten görüntü işlemde veya, zaten bekleyen bir işlem engellemez emin olun.Bu tür bir işlem sürüyor durumunda girme işlemi yazdırılma beklemeniz gerekir.

Private Async Function FinishOneGroupAsync(urls As List(Of String), contentTasks As Task(Of Byte())(), grp As Char) As Task

    ' Wait for the previous group to finish displaying results.
    If pendingWork IsNot Nothing Then
        Await pendingWork
    End If

    Dim total = 0

    ' contentTasks is the array of Tasks that was created in AccessTheWebAsync.
    For i As Integer = 0 To contentTasks.Length - 1
        ' Await the download of a particular URL, and then display the URL and
        ' its length.
        Dim content As Byte() = Await contentTasks(i)
        DisplayResults(urls(i), content, i, grp)
        total += content.Length
    Next

    ' Display the total count for all of the websites.
    ResultsTextBox.Text &=
        String.Format(vbCrLf & vbCrLf & "TOTAL bytes returned:  " & total & vbCrLf)
End Function
private async Task FinishOneGroupAsync(List<string> urls, Task<byte[]>[] contentTasks, char grp)
{
    // ***Wait for the previous group to finish displaying results.
    if (pendingWork != null) await pendingWork;

    int total = 0;

    // contentTasks is the array of Tasks that was created in AccessTheWebAsync.
    for (int i = 0; i < contentTasks.Length; i++)
    {
        // Await the download of a particular URL, and then display the URL and
        // its length.
        byte[] content = await contentTasks[i];
        DisplayResults(urls[i], content, i, grp);
        total += content.Length;
    }

    // Display the total count for all of the websites.
    ResultsTextBox.Text +=
        string.Format("\r\n\r\nTOTAL bytes returned:  {0}\r\n", total);
}

Bu örnek kodun içine girmek değişiklikleri yapıştırarak çalıştırabilirsiniz Uygulama oluşturma, veya yönergeleri takip edebilirsiniz Uygulama yükleme örneği indirebilir ve QueueResults projeyi çalıştırın.

JJ651641.collapse_all(tr-tr,VS.110).gifİlgi çekici noktalar

Bu örnek nasıl çalıştığını çıktı pound işareti (#) ile başlayan bilgi satırları açıklığa kavuşturmak.

Çıktı aşağıdaki düzenlerden gösterilmiştir.

  • Bir grup, önceki Grup çıktı görüntülüyor, ancak önceki grubun çıkış görüntüsünü kesintiye değil başlatılabilir.

    #Starting group A.
    #Task assigned for group A. Download tasks are active.
    
    A-1. msdn.microsoft.com/en-us/library/hh191443.aspx                87389
    A-2. msdn.microsoft.com/en-us/library/aa578028.aspx               207089
    A-3. msdn.microsoft.com/en-us/library/jj155761.aspx                30870
    A-4. msdn.microsoft.com/en-us/library/hh290140.aspx               119037
    A-5. msdn.microsoft.com/en-us/library/hh524395.aspx                71260
    
    #Starting group B.
    #Task assigned for group B. Download tasks are active.
    
    A-6. msdn.microsoft.com/en-us/library/ms404677.aspx               199186
    A-7. msdn.microsoft.com                                            53078
    A-8. msdn.microsoft.com/en-us/library/ff730837.aspx               148010
    
    TOTAL bytes returned:  915919
    
    B-1. msdn.microsoft.com/en-us/library/hh191443.aspx                87388
    B-2. msdn.microsoft.com/en-us/library/aa578028.aspx               207089
    B-3. msdn.microsoft.com/en-us/library/jj155761.aspx                30870
    
    #Group A is complete.
    
    B-4. msdn.microsoft.com/en-us/library/hh290140.aspx               119027
    B-5. msdn.microsoft.com/en-us/library/hh524395.aspx                71260
    B-6. msdn.microsoft.com/en-us/library/ms404677.aspx               199186
    B-7. msdn.microsoft.com                                            53078
    B-8. msdn.microsoft.com/en-us/library/ff730837.aspx               148010
    
    TOTAL bytes returned:  915908
    
  • pendingWork Görev null (Nothing Visual Basic) başındaki FinishOneGroupAsync yalnızca Grup a, başlatılan ilk.Grup a taşınmadığından henüz tamamlanmamış await ifade ulaştığında FinishOneGroupAsync.Bu nedenle, denetim için döndürülen taşınmadığından AccessTheWebAsyncve ilk atama için pendingWork taşınmadığından oluştu.

  • Aşağıdaki iki satırı birlikte çıktıda her zaman görünür.Bir grubun işlem başlatılırken arasında kod hiçbir zaman kesintiye StartButton_Click ve grup için bir görev atama pendingWork.

    #Starting group B.
    #Task assigned for group B. Download tasks are active.
    

    Bir grup girdikten sonra StartButton_Click, işlem girene kadar await ifade işlemi yoksa FinishOneGroupAsync.Bu nedenle, başka bir işlem denetimi sırasında o segment kodunun kazanabilirler.

İnceleme ve örnek uygulama çalıştırma

Örnek uygulama daha iyi anlamak için karşıdan kendiniz yapılandırmak veya app Uygulama olmadan bu konunun sonundaki kodu gözden geçirin.

[!NOT]

Windows Presentation Foundation (wpf) masaüstü uygulaması örneği çalıştırmak için Visual Studio 2012 sahip Visual Studio Express 2012 için Windows Masaüstü, veya bilgisayarınızda yüklü .NET Framework 4.5.

Örnek olarak çalıştırmak için bir Windows Mağazası app, Windows 8 bilgisayarınızda yüklü olması gerekir.Ayrıca, bu örnek Visual Studio'dan çalıştırmak istiyorsanız, Visual Studio 2012 de olmalıdır veya Visual Studio Express 2012 Windows 8 yüklü.Visual Studio 2010 için .NET Framework 4.5 hedeflenen projeler yüklenemiyor.

JJ651641.collapse_all(tr-tr,VS.110).gifUygulama yükleme

  1. Sıkıştırılmış dosyadan yükleme zaman uyumsuz örnekleri: .NET Masaüstü Apps içinde yeniden giriş veya zaman uyumsuz örnekleri: Windows mağaza Apps içinde yeniden giriş.

  2. Karşıdan yüklediğiniz dosyasını indirip sıkıştırmasını açın ve Visual Studio başlatın.

  3. Menü çubuğunda, Dosya, , Proje/Çözüm seçeneklerini belirleyin.

  4. Sıkıştırması açılmış örnek kodu içeren klasöre gidin ve sonra çözüm (.sln) dosyasını açın.

  5. İçinde Çözüm Gezgini, çalıştırın ve sonra seçmek istediğiniz proje için kısayol menüsünü aç StartUpProject Ayarla.

  6. Yapı ve proje çalıştırmak için ctrl + F5 tuşları seçin.

JJ651641.collapse_all(tr-tr,VS.110).gifUygulama oluşturma

Aşağıdaki bölümlerde örnek olarak veya wpf uygulaması oluşturmak için kod sağlayan bir Windows Mağazası app.

wpf uygulaması oluşturma

  1. Visual Studio 2012 başlatın.

  2. Menü çubuğunda Dosya, Yeni, Proje'yi seçin.

    Yeni Proje iletişim kutusu açılır.

  3. İçinde Yüklü Şablonlar bölmesinde genişletin Visual Basic veya **Visual C#**ve sonra genişletin Windows.

  4. Proje türleri listesinde seçin wpf uygulaması.

  5. Proje adı WebsiteDownloadWPFve sonra Tamam düğmesi.

    Çözüm Gezgini'nde yeni proje görüntülenir.

  6. Visual Studio Kod Düzenleyicisi'nde seçin MainWindow.xaml sekme.

    Sekmesi görünür değilse, MainWindow.xaml içinde için kısayol menüsünü aç Çözüm Gezginive sonra seçin Görünüm kodu.

  7. İçinde xaml MainWindow.xaml görüntülemek, kodu aşağıdaki kod ile değiştirin.

    <Window x:Class="MainWindow"
        xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="using:WebsiteDownloadWPF"
        xmlns:d="https://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="https://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d">
    
        <Grid Width="517" Height="360">
            <Button x:Name="StartButton" Content="Start" HorizontalAlignment="Left" Margin="-1,0,0,0" VerticalAlignment="Top" Click="StartButton_Click" Height="53" Background="#FFA89B9B" FontSize="36" Width="518"  />
            <TextBox x:Name="ResultsTextBox" HorizontalAlignment="Left" Margin="-1,53,0,-36" TextWrapping="Wrap" VerticalAlignment="Top" Height="343" FontSize="10" ScrollViewer.VerticalScrollBarVisibility="Visible" Width="518" FontFamily="Lucida Console" />
        </Grid>
    </Window>
    
    <Window x:Class="WebsiteDownloadWPF.MainWindow"
        xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="using:WebsiteDownloadWPF"
        xmlns:d="https://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="https://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d">
    
        <Grid Width="517" Height="360">
            <Button x:Name="StartButton" Content="Start" HorizontalAlignment="Left" Margin="-1,0,0,0" VerticalAlignment="Top" Click="StartButton_Click" Height="53" Background="#FFA89B9B" FontSize="36" Width="518"  />
            <TextBox x:Name="ResultsTextBox" HorizontalAlignment="Left" Margin="-1,53,0,-36" TextWrapping="Wrap" VerticalAlignment="Top" Height="343" FontSize="10" ScrollViewer.VerticalScrollBarVisibility="Visible" Width="518" FontFamily="Lucida Console" />
        </Grid>
    </Window>
    

    Metin kutusu ve bir düğme içeren basit bir pencere görünür Tasarım görünümünü MainWindow.xaml.

  8. Başvuru için System.Net.Http.

  9. İçinde Çözüm Gezgini, MainWindow.xaml.vb veya MainWindow.xaml.cs için kısayol menüsünü açın ve sonra seçin Görünüm kodu.

  10. MainWindow.xaml.vb veya MainWindow.xaml.cs, kodu aşağıdaki kod ile değiştirin.

    ' Add the following Imports statements, and add a reference for System.Net.Http.
    Imports System.Net.Http
    Imports System.Threading
    
    Class MainWindow
    
        Private Async Sub StartButton_Click(sender As Object, e As RoutedEventArgs)
            ' This line is commented out to make the results clearer in the output.
            'ResultsTextBox.Text = ""
    
            Try
                Await AccessTheWebAsync()
    
            Catch ex As Exception
                ResultsTextBox.Text &= vbCrLf & "Downloads failed."
    
            End Try
        End Sub
    
    
        Private Async Function AccessTheWebAsync() As Task
    
            ' Declare an HttpClient object.
            Dim client = New HttpClient()
    
            ' Make a list of web addresses.
            Dim urlList As List(Of String) = SetUpURLList()
    
            Dim total = 0
            Dim position = 0
    
            For Each url In urlList
                ' GetByteArrayAsync returns a task. At completion, the task
                ' produces a byte array.
                Dim urlContents As Byte() = Await client.GetByteArrayAsync(url)
    
                position += 1
                DisplayResults(url, urlContents, position)
    
                ' Update the total.
                total += urlContents.Length
            Next
    
            ' Display the total count for all of the websites.
            ResultsTextBox.Text &=
                String.Format(vbCrLf & vbCrLf & "TOTAL bytes returned:  " & total & vbCrLf)
        End Function
    
    
        Private Function SetUpURLList() As List(Of String)
            Dim urls = New List(Of String) From
            {
                "https://msdn.microsoft.com/en-us/library/hh191443.aspx",
                "https://msdn.microsoft.com/en-us/library/aa578028.aspx",
                "https://msdn.microsoft.com/en-us/library/jj155761.aspx",
                "https://msdn.microsoft.com/en-us/library/hh290140.aspx",
                "https://msdn.microsoft.com/en-us/library/hh524395.aspx",
                "https://msdn.microsoft.com/en-us/library/ms404677.aspx",
                "https://msdn.microsoft.com",
                "https://msdn.microsoft.com/en-us/library/ff730837.aspx"
            }
            Return urls
        End Function
    
    
        Private Sub DisplayResults(url As String, content As Byte(), pos As Integer)
            ' 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.
    
            ' Strip off the "http:'".
            Dim displayURL = url.Replace("http://", "")
            ' Display position in the URL list, the URL, and the number of bytes.
            ResultsTextBox.Text &= String.Format(vbCrLf & "{0}. {1,-58} {2,8}", pos, displayURL, content.Length)
        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 directives, and add a reference for System.Net.Http.
    using System.Net.Http;
    using System.Threading;
    
    namespace WebsiteDownloadWPF
    {
        public partial class MainWindow : Window
        {
            public MainWindow()
            {
                InitializeComponent();
            }
    
    
            private async void StartButton_Click(object sender, RoutedEventArgs e)
            {
                // This line is commented out to make the results clearer in the output.
                //ResultsTextBox.Text = "";
    
                try
                {
                    await AccessTheWebAsync();
                }
                catch (Exception)
                {
                    ResultsTextBox.Text += "\r\nDownloads failed.";
                }
            }
    
    
            private async Task AccessTheWebAsync()
            {
                // Declare an HttpClient object.
                HttpClient client = new HttpClient();
    
                // Make a list of web addresses.
                List<string> urlList = SetUpURLList();
    
                var total = 0;
                var position = 0;
    
                foreach (var url in urlList)
                {
                    // GetByteArrayAsync returns a task. At completion, the task
                    // produces a byte array.
                    byte[] urlContents = await client.GetByteArrayAsync(url);
    
                    DisplayResults(url, urlContents, ++position);
    
                    // Update the total.
                    total += urlContents.Length;
                }
    
                // Display the total count for all of the websites.
                ResultsTextBox.Text +=
                    string.Format("\r\n\r\nTOTAL bytes returned:  {0}\r\n", total);
            }
    
    
            private List<string> SetUpURLList()
            {
                List<string> urls = new List<string> 
                { 
                    "https://msdn.microsoft.com/en-us/library/hh191443.aspx",
                    "https://msdn.microsoft.com/en-us/library/aa578028.aspx",
                    "https://msdn.microsoft.com/en-us/library/jj155761.aspx",
                    "https://msdn.microsoft.com/en-us/library/hh290140.aspx",
                    "https://msdn.microsoft.com/en-us/library/hh524395.aspx",
                    "https://msdn.microsoft.com/en-us/library/ms404677.aspx",
                    "https://msdn.microsoft.com",
                    "https://msdn.microsoft.com/en-us/library/ff730837.aspx"
                };
                return urls;
            }
    
    
            private void DisplayResults(string url, byte[] content, int pos)
            {
                // 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.
    
                // Strip off the "http://".
                var displayURL = url.Replace("http://", "");
                // Display position in the URL list, the URL, and the number of bytes.
                ResultsTextBox.Text += string.Format("\n{0}. {1,-58} {2,8}", pos, displayURL, content.Length);
            }
        }
    }
    
  11. Programı çalıştırın ve sonra seçmek için ctrl + F5 tuşları seçin Start düğmesini birkaç kez.

  12. Yaptığınız değişiklikleri Başlat düğmesini devre dışı bırak, İptal etmek ve işlemi yeniden başlatın, veya Birden çok işlemi çalıştırmak ve sıraya çıktı yeniden giriş işlemek için.

Windows Store app oluşturmak için

  1. Visual Studio 2012 başlatın.

  2. Menü çubuğunda Dosya, Yeni, Proje'yi seçin.

    Yeni Proje iletişim kutusu açılır.

  3. İçinde yüklü, şablonları kategori genişletin Visual Basic veya **Visual C#**ve genişletin Windows deposu.

  4. Proje türleri listesinde seçin Boş App (xaml).

  5. Proje adı WebsiteDownloadWinve sonra Tamam düğmesi.

    Çözüm Gezgini'nde yeni proje görüntülenir.

  6. İçinde Çözüm Gezgini, MainPage.xaml için kısayol menüsünü açın ve sonra seçin açık.

  7. İçinde xaml MainPage.xaml, pencerenin kodu aşağıdaki kod ile değiştirin.

    <Page
        x:Class="WebsiteDownloadWin.MainPage"
        xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="using:WebsiteDownloadWin"
        xmlns:d="https://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="https://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d" FontSize="12">
    
        <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
            <Button x:Name="StartButton" Content="Start" HorizontalAlignment="Left" Margin="325,77,0,0" VerticalAlignment="Top" Click="StartButton_Click" Height="145" Background="#FFA89B9B" FontSize="36" Width="711"  />
            <TextBox x:Name="ResultsTextBox" HorizontalAlignment="Left" Margin="325,222,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Height="546" FontSize="10" ScrollViewer.VerticalScrollBarVisibility="Visible" Width="711" FontFamily="Lucida Console" />
        </Grid>
    </Page>
    

    Bir metin kutusu içeren basit bir pencere ve bir Başlangıç düğmesi görünür Tasarım MainPage.xaml penceresi.

  8. İçinde Çözüm Gezgini, MainPage.xaml.vb veya MainPage.xaml.cs için kısayol menüsünü açın ve sonra seçin Görünüm kodu.

  9. MainPage.xaml.vb veya MainPage.xaml.cs kodu aşağıdaki kod ile değiştirin.

    ' Add the following Imports statements.
    Imports System.Threading.Tasks
    Imports System.Threading
    Imports System.Net.Http
    
    Public NotInheritable Class MainPage
        Inherits Page
    
        Protected Overrides Sub OnNavigatedTo(e As Navigation.NavigationEventArgs)
        End Sub
    
    
        Private Async Sub StartButton_Click(sender As Object, e As RoutedEventArgs)
            ' This line is commented out to make the results clearer in the output.
            'ResultsTextBox.Text = ""
    
            Try
                Await AccessTheWebAsync()
    
            Catch ex As Exception
                ResultsTextBox.Text &= vbCrLf & "Downloads failed."
    
            End Try
        End Sub
    
    
        Private Async Function AccessTheWebAsync() As Task
    
            ' Declare an HttpClient object.
            Dim client = New HttpClient()
    
            ' Make a list of web addresses.
            Dim urlList As List(Of String) = SetUpURLList()
    
            Dim total = 0
            Dim position = 0
    
            For Each url In urlList
                ' GetByteArrayAsync returns a task. At completion, the task
                ' produces a byte array.
                Dim urlContents As Byte() = Await client.GetByteArrayAsync(url)
    
                position += 1
                DisplayResults(url, urlContents, position)
    
                ' Update the total.
                total += urlContents.Length
            Next
    
            ' Display the total count for all of the websites.
            ResultsTextBox.Text &=
                String.Format(vbCrLf & vbCrLf & "TOTAL bytes returned:  " & total & vbCrLf)
        End Function
    
    
        Private Function SetUpURLList() As List(Of String)
            Dim urls = New List(Of String) From
            {
                "https://msdn.microsoft.com/en-us/library/hh191443.aspx",
                "https://msdn.microsoft.com/en-us/library/aa578028.aspx",
                "https://msdn.microsoft.com/en-us/library/jj155761.aspx",
                "https://msdn.microsoft.com/en-us/library/hh290140.aspx",
                "https://msdn.microsoft.com/en-us/library/hh524395.aspx",
                "https://msdn.microsoft.com/en-us/library/ms404677.aspx",
                "https://msdn.microsoft.com",
                "https://msdn.microsoft.com/en-us/library/ff730837.aspx"
            }
            Return urls
        End Function
    
    
        Private Sub DisplayResults(url As String, content As Byte(), pos As Integer)
            ' 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.
    
            ' Strip off the "http:'".
            Dim displayURL = url.Replace("http://", "")
            ' Display position in the URL list, the URL, and the number of bytes.
            ResultsTextBox.Text &= String.Format(vbCrLf & "{0}. {1,-58} {2,8}", pos, displayURL, content.Length)
        End Sub
    End Class
    
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using Windows.Foundation;
    using Windows.Foundation.Collections;
    using Windows.UI.Xaml;
    using Windows.UI.Xaml.Controls;
    using Windows.UI.Xaml.Controls.Primitives;
    using Windows.UI.Xaml.Data;
    using Windows.UI.Xaml.Input;
    using Windows.UI.Xaml.Media;
    using Windows.UI.Xaml.Navigation;
    
    // Add the following using directives. 
    using System.Threading.Tasks;
    using System.Threading;
    using System.Net.Http;
    
    
    namespace WebsiteDownloadWin
    {
        public sealed partial class MainPage : Page
        {
            public MainPage()
            {
                this.InitializeComponent();
            }
    
            private async void StartButton_Click(object sender, RoutedEventArgs e)
            {
                // This line is commented out to make the results clearer in the output.
                //ResultsTextBox.Text = "";
    
                try
                {
                    await AccessTheWebAsync();
                }
                catch (Exception)
                {
                    ResultsTextBox.Text += "\r\nDownloads failed.";
                }
            }
    
    
            private async Task AccessTheWebAsync()
            {
                // Declare an HttpClient object.
                HttpClient client = new HttpClient();
    
                // Make a list of web addresses.
                List<string> urlList = SetUpURLList();
    
                var total = 0;
                var position = 0;
    
                foreach (var url in urlList)
                {
                    // GetByteArrayAsync returns a task. At completion, the task
                    // produces a byte array.
                    byte[] urlContents = await client.GetByteArrayAsync(url);
    
                    DisplayResults(url, urlContents, ++position);
    
                    // Update the total.
                    total += urlContents.Length;
                }
    
                // Display the total count for all of the websites.
                ResultsTextBox.Text +=
                    string.Format("\r\n\r\nTOTAL bytes returned:  {0}\r\n", total);
            }
    
    
            private List<string> SetUpURLList()
            {
                List<string> urls = new List<string> 
                { 
                    "https://msdn.microsoft.com/en-us/library/hh191443.aspx",
                    "https://msdn.microsoft.com/en-us/library/aa578028.aspx",
                    "https://msdn.microsoft.com/en-us/library/jj155761.aspx",
                    "https://msdn.microsoft.com/en-us/library/hh290140.aspx",
                    "https://msdn.microsoft.com/en-us/library/hh524395.aspx",
                    "https://msdn.microsoft.com/en-us/library/ms404677.aspx",
                    "https://msdn.microsoft.com",
                    "https://msdn.microsoft.com/en-us/library/ff730837.aspx"
                };
                return urls;
            }
    
    
            private void DisplayResults(string url, byte[] content, int pos)
            {
                // 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.
    
                // Strip off the "http://".
                var displayURL = url.Replace("http://", "");
                // Display position in the URL list, the URL, and the number of bytes.
                ResultsTextBox.Text += string.Format("\n{0}. {1,-58} {2,8}", pos, displayURL, content.Length);
            }
        }
    }
    
  10. Programı çalıştırın ve sonra seçmek için ctrl + F5 tuşları seçin Start düğmesini birkaç kez.

  11. Yaptığınız değişiklikleri Başlat düğmesini devre dışı bırak, İptal etmek ve işlemi yeniden başlatın, veya Birden çok işlemi çalıştırmak ve sıraya çıktı yeniden giriş işlemek için.

Ayrıca bkz.

Görevler

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

Kavramlar

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

Diğer Kaynaklar

Zaman uyumsuz programlama (Windows Store apps)

Quickstart: C# veya Visual Basic içinde zaman uyumsuz API'lerini çağırmak