WhenAny: .NET Framework と Windows ランタイム間のブリッジ (C# および Visual Basic)

このトピックの例では、完了した順序で非同期タスクを処理する .NET Framework メソッドのブログ フィードを非同期にダウンロードする Windows ランタイム の型をパッケージ化します。型の詳細については、SyndicationClient" "を参照してください。メソッドに関する詳細については、Task.WhenAnyを参照してください。

これらの機能をまとめることによって、複数のブログ フィードを同時にダウンロードし、結果を処理し、完了と同時に開始できます。1 個のフィードよりもすばやくダウンロードした場合、結果は先頭に表示されます。SyndicationClient のメソッドを使用して、フィードを簡単にダウンロードします; Task.WhenAny のメソッドを使用して、より簡単に終了するダウンロードな次のフィードを識別できます。

[!メモ]

例を実行するには、コンピューターにインストールされている Windows 8 が必要です。また、Visual Studio で例を実行する場合、Visual Studio 2012 が Visual Studio には、Windows 8 の 2012 を表します。 あるインストールします。

次のコードは Windows ランタイム と .NET Frameworkからこれらの機能をパッケージ化します:

Try
    Dim feedsQuery As IEnumerable(Of Task(Of SyndicationFeed)) =
        From uri In uriList
        Select client.RetrieveFeedAsync(uri).AsTask()
    ' AsTask changes the returns from RetrieveFeedAsync into tasks.

    ' Run the query to start all the asynchronous processes.
    Dim blogFeedTasksList As List(Of Task(Of SyndicationFeed)) = feedsQuery.ToList()

    Dim feed As SyndicationFeed

    ' Repeat the following until there are no tasks left:
    '    - Grab the first one that finishes.
    '    - Retrieve the results from the task (what the return statement 
    '      in RetrieveFeedAsync returns).
    '    - Remove the task from the list.
    '    - Display the results.
    While blogFeedTasksList.Count > 0
        Dim nextTask As Task(Of SyndicationFeed) = Await Task.WhenAny(blogFeedTasksList)
        feed = Await nextTask
        blogFeedTasksList.Remove(nextTask)
        DisplayResults(feed)
    End While

Catch ex As Exception
    ResultsTextBox.Text =
        "Page could not be loaded." & vbCrLf & "Exception: " & ex.ToString()
End Try
try
{
    IEnumerable<Task<SyndicationFeed>> feedsQuery =
            from uri in uriList
            // AsTask changes the returns from RetrieveFeedAsync into tasks.
            select client.RetrieveFeedAsync(uri).AsTask();

    // Run the query to start all the asynchronous processes.
    List<Task<SyndicationFeed>> blogFeedTasksList = feedsQuery.ToList();

    SyndicationFeed feed;

    // Repeat the following until no tasks remain:
    //    - Grab the first one that finishes.
    //    - Retrieve the results from the task (what the return statement 
    //      in RetrieveFeedAsync returns).
    //    - Remove the task from the list.
    //    - Display the results.
    while (blogFeedTasksList.Count > 0)
    {
        Task<SyndicationFeed> nextTask = await Task.WhenAny(blogFeedTasksList);
        feed = await nextTask;                    
        blogFeedTasksList.Remove(nextTask);
        DisplayResults(feed);
    }
}
catch (Exception ex)
{
    ResultsTextBox.Text =
        "Page could not be loaded.\n\r" + "Exception: " + ex.ToString();
}

次の例は、行のような出力が生成されます。各ブログの場合、はブログの投稿のタイトルおよび日付とそれに続くブログのタイトルを示します。

Developing for Windows
     New blog for Windows 8 app developers, 5/1/2012 2:33:02 PM -07:00
     Trigger-Start Services Recipe, 3/24/2011 2:23:01 PM -07:00
     . . .
     Countdown to PDC10, 10/26/2010 4:11:28 PM -07:00

Extreme Windows Blog
     PDXLAN 20: “Epidemic” Custom PC by Jon Hansz, 7/30/2012 2:31:35 PM -07:00
     Samsung Notebook Series 9: Taking Thin and Light to the Extreme, 7/23/2012 12:06:03 PM -07:00
     . . .
     AMD Unveils A-Series APUs, 6/13/2011 9:34:01 PM -07:00

Blogging Windows
     Windows 8 has reached the RTM milestone, 8/1/2012 9:00:00 AM -07:00
     Windows 8 will be available on…, 7/18/2012 1:09:00 PM -07:00
     . . .
     More buzz from BUILD – Developers get their devices!, 9/13/2011 7:47:57 PM -07:00

Springboard Series Blog
     What to Expect in User Experience Virtualization Beta 2, 6/25/2012 11:03:27 PM -07:00
     Introducing Microsoft BitLocker Administration 2.0 Beta, 6/12/2012 8:08:23 AM -07:00
     . . .
     The Springboard Series Visits Lima, Peru, 11/18/2011 5:27:37 AM -08:00

このトピックの残りの部分では、の動作方法の詳細を作成する例を提供します。

このアプリケーションを実行するには、コンピューターにインストール Visual Studio 2012 と Windows 8 が必要です。

このトピックは、次のセクションで構成されています。

  • 例のセットアップ オプション
  • 初期コードの理解
  • 初期コードの拡張
  • 初期コードのダウンロード
  • 完成したアプリケーションのダウンロード
  • 初期コードをビルド
  • 完成したアプリケーションをビルド
  • 関連トピック

例のセットアップ オプション

例には Quickstart: 非同期プログラミングの予想の演算子を使用する、ブログ リーダーに基づいています。しかし、このトピックの初期コードは、1 の代わりに複数のブログ フィードをダウンロードします。

初期コードは、ブログ フィードを順番にダウンロードするには Windows ランタイム の機能を使用します。つまり、ブログ フィードは URL のコレクションに示されている順序でダウンロードされます。完成したアプリケーションは .NET Framework からブログ フィードをダウンロードする機能を完了する順序追加します。

次の方法のいずれかを設定するコードの例:

  • 初期コード。

    • 初期コードのダウンロードの手順に従って初期コードをダウンロードできます

    • 初期コードを独自 初期コードをビルドの手順に従って作成できます。

    • これを実行しないで 初期コードをビルドにスクロールして初期コードを確認できます。

  • 終了するアプリケーション。

    • 完成したアプリケーションのダウンロードの手順に従って終了するアプリケーションをダウンロードできます

    • アプリケーションを独自 完成したアプリケーションをビルドの手順に従って作成できます。

    • これを実行しないで 完成したアプリケーションをビルドにスクロールによって終了するアプリケーションを確認できます。

初期コードの理解 のセクションでは、基本的な読み取りキーについて説明します。

初期コードの拡張 のセクションでは AsTaskTask.WhenAnyを追加して、コードを変更する方法を示します。

初期コードの理解

初期コードは、URI の一覧の各 URI からのブログ フィードをダウンロードするには SyndicationClient のメソッドを RetrieveFeedAsync使用します。このメソッドの各呼び出しは、進行中の非同期操作を表すインスタンス IAsyncOperationWithProgress を返します。予期されると、非同期操作は、ダウンロードしたブログ フィードに関する情報を含むインスタンス SyndicationFeed を生成します。

コードは URI のリストの各エントリに RetrieveFeedAsync を適用するクエリを定義します。を実行すると、クエリは IAsyncOperationWithProgress のインスタンスのコレクションを返します。

Dim feedsQuery As IEnumerable(Of IAsyncOperationWithProgress(Of SyndicationFeed, 
                                                                RetrievalProgress)) =
                                                From uri In uriList
                                                Select client.RetrieveFeedAsync(uri)
IEnumerable<IAsyncOperationWithProgress<SyndicationFeed, 
    RetrievalProgress>> feedsQuery = from uri in uriList
                                     select client.RetrieveFeedAsync(uri);

ToList<TSource> は、次のコードに示すように、クエリを実行し、非同期プロセスを開始します。

Dim blogFeedOpsList As List(Of IAsyncOperationWithProgress(Of SyndicationFeed, 
                                                           RetrievalProgress)) =
                                               feedsQuery.ToList()
List<IAsyncOperationWithProgress<SyndicationFeed, 
    RetrievalProgress>> blogFeedOpsList = feedsQuery.ToList();

この時点で、IAsyncOperationWithProgress のアクティブなインスタンスの一覧があります。まだ最終的な結果を得るために、各インスタンスを待機する必要があります。

次のループは SyndicationFeed の結果を取得するには IAsyncOperationWithProgress の各インスタンスを待機します。

Dim feed As SyndicationFeed
For Each blogFeedOp In blogFeedOpsList
    ' The Await operator retrieves the final result (a SyndicationFeed instance)
    ' from each IAsyncOperation instance.
    feed = Await blogFeedOp
    DisplayResults(feed)
Next
SyndicationFeed feed;
foreach (var blogFeedOp in blogFeedOpsList)
{
    // The await operator retrieves the final result (a SyndicationFeed instance)
    // from each IAsyncOperation instance.
    feed = await blogFeedOp;
    DisplayResults(feed);
}

トピックの最後に Building the Starter Code のセクションのプログラムのこのバージョンを確認できます。

Windows ランタイム の非同期 API Quickstart: 非同期プログラミングの予想の演算子を使用するを使用したプログラミングに関する詳細情報を検索できます。

初期コードの拡張

初期コードは SyndicationClient がブログ フィードのダウンロードを簡単にすることを示します。例を実行する残りの手順は、ダウンロードが URI の一覧に表示される順序の代わりに完了する順序ブログ フィードを処理できるようにすることです。

拡張機能の実行には Task.WhenAny のメソッドです。非同期処理のコレクションに WhenAny を適用すると、メソッドは、が完了するまで待機する時間を短縮できる最初のプロセスを返します。この例では、ブログ フィードの情報を表示する順序は重要ではありません。1 種類のダウンロードの場合、別のブログの結果には、最初に表示できます。状態は、次の 1 点を除き WhenAny の完全な方法です: WhenAny、タスクのコレクションを要求します。

JJ635140.collapse_all(ja-jp,VS.110).gifAsTask の開始

WhenAny は Task または Task<TResult> のインスタンスのコレクションが必要ですが、ブログをダウンロードする SyndicationClient のメソッドがリターン IAsyncOperationWithProgress にインスタンスに示します。したがって、アプリケーションは Windows ランタイム から IAsyncOperationWithProgress のオブジェクトと .NET Framework の Task のオブジェクト間で繋がなければ必要があります。

.NET Framework が遷移を実行するには AsTask の拡張メソッドを提供します。IAsyncOperationWithProgress のインスタンスの AsTask を起動すると、AsTask は、非同期操作を表すタスクを返します。タスクは IAsyncOperationWithProgress の対応するインスタンスが完了すると、タスク インスタンスの結果、例外があります。と完了します。

したがって、次のコードとして RetrieveFeedAsync の戻り値は、IAsyncOperationWithProgress の各インスタンスの AsTask を開始します。コードはタスクの変更を反映する変数の名前を変更し、わかりやすくするために明示的な型指定を使用しています。

Dim feedsQuery As IEnumerable(Of Task(Of SyndicationFeed)) =
    From uri In uriList
    Select client.RetrieveFeedAsync(uri).AsTask()
' AsTask changes the returns from RetrieveFeedAsync into tasks.

' Run the query to start all the asynchronous processes.
Dim blogFeedTasksList As List(Of Task(Of SyndicationFeed)) = feedsQuery.ToList()
IEnumerable<Task<SyndicationFeed>> feedsQuery =
        from uri in uriList
        // AsTask changes the returns from RetrieveFeedAsync into tasks.
        select client.RetrieveFeedAsync(uri).AsTask();

// Run the query to start all the asynchronous processes.
List<Task<SyndicationFeed>> blogFeedTasksList = feedsQuery.ToList();

[!メモ]

AsTask は、を認識しないことをプログラムする非同期の重要な役割を果たします。コンパイラは、次のコードに示すよう IAsyncAction または IAsyncOperation のインスタンスが演算子を追加するたびに AsTask を使用します。

JJ635140.collapse_all(ja-jp,VS.110).gifWhenAny の適用

変換の最後の手順では、アプリケーションに Task.WhenAny のメソッドを追加します。WhenAny は、タスク (blogFeedTasksList) と戻り値のコレクションに完了したコレクションの最初のタスク適用されます。つまり、WhenAny 必要な場合は、最初に終了したタスクに評価するタスクを返します。

次のステートメントは WhenAny を呼び出し、結果を待機します。コードは結果をより明確に示す明示的な型指定を使用しています。

Dim nextTask As Task(Of SyndicationFeed) = Await Task.WhenAny(blogFeedTasksList)
Task<SyndicationFeed> nextTask = await Task.WhenAny(blogFeedTasksList);

次のコードは前のステートメントの 2 種類のステートメントに休憩とどうなるかを明確にするために同じことを操作できます。最初のステートメントは WhenAnyを呼び出し、2 番目のステートメントでは結果を待機します。

' WhenAny returns a task that, when awaited, produces a task.
' Call:
Dim whenAnyTask As Task(Of Task(Of SyndicationFeed)) = Task.WhenAny(blogFeedTasksList)
' Await:
Dim nextTask As Task(Of SyndicationFeed) = Await whenAnyTask
// WhenAny returns a task that, when awaited, produces a task.
// Call:
Task<Task<SyndicationFeed>> whenAnyTask = Task.WhenAny(blogFeedTasksList);
// Await:
Task<SyndicationFeed> nextTask = await whenAnyTask;

最後に、もう一度処理しないように、最初に終了した場合は、一覧から nextTask からタスクを削除する必要があります SyndicationFeed 結果 (のインスタンス) を取得するには nextTask を待ちます。

feed = Await nextTask
blogFeedTasksList.Remove(nextTask)
feed = await nextTask;                    
blogFeedTasksList.Remove(nextTask);

blogFeedTasksListで各タスクに対して、これらの手順を実行するには、while ループを使用します。

While blogFeedTasksList.Count > 0
    Dim nextTask As Task(Of SyndicationFeed) = Await Task.WhenAny(blogFeedTasksList)
    feed = Await nextTask
    blogFeedTasksList.Remove(nextTask)
    DisplayResults(feed)
End While
while (blogFeedTasksList.Count > 0)
{
    Task<SyndicationFeed> nextTask = await Task.WhenAny(blogFeedTasksList);
    feed = await nextTask;                    
    blogFeedTasksList.Remove(nextTask);
    DisplayResults(feed);
}

トピックの最後に 完成したアプリケーションをビルド のセクションのプログラムのこのバージョンを確認できます。プロジェクトをダウンロードまたは 完成したアプリケーションのダウンロード の手順を実行できます。

Caution メモ注意

ループの WhenAny の使用は、例に示すように、いくつかのタスクを格納する問題の場合、問題なく使用できます。ただし、他の方法では、複数のタスクが処理する場合よりも効率的です。詳細については、" "を参照してください。タスクを完了したとして処理

初期コードのダウンロード

この例の初期コードは、単一の例: .NET から Windows へのバインドからダウンロードできます。インターネットにアクセスできない場合は、初期コードを作成するこのトピックの最後に 初期コードをビルド の指示に従います。

コードをダウンロードした後、次の手順を実行して、これを開き、移動します。

  1. ダウンロードした展開し、を Visual Studio 2012ファイルを起動します。

  2. メニュー バーで [ファイル][開く][プロジェクト/ソリューション] の順に選択します。

  3. 配置されたサンプル コードを保持する移動し、AsTaskWhenAnyDemoVB または AsTaskWhenAnyDemoCS のソリューション (.sln) ファイルにフォルダーを開きます。

  4. [ソリューション エクスプローラー] では、[SequentialBlogReader] のプロジェクトのショートカット メニューを開き、[スタートアップ プロジェクトに設定] を選択します。

  5. プロジェクトをビルドして実行するには、F5 キーを選択します。

  6. コードを同じ順序で結果が常に表示されることを確認する複数回実行します。

トピックの最後に 初期コードをビルド のセクションの MainPage.xaml.vb ファイルを確認できます。

例には Quickstart: 非同期プログラミングの予想の演算子を使用する、ブログ リーダーに基づいています。しかし、このトピックの初期コードは、1 の代わりに複数のブログ フィードをダウンロードします。

アプリケーションに行うことができる拡張子とさまざまなアップグレードの詳細については、" "を参照してください。ブログ リーダーを作成します。

完成したアプリケーションのダウンロード

独自の例をビルドするには、完全な例をダウンロードできます。初期コードのダウンロード のセクションの指示に従います。ただし、[スタートアップ プロジェクト] として [WhenAnyBlogReader] を選択します。

プログラムをブログ フィードが異なる順序で表示されることを確認する複数回実行します。

トピックの最後に 完成したアプリケーションをビルド のセクションの MainPage.xaml.vb ファイルを確認できます。

初期コードをビルド

このトピックの例は、単一の例: .NET から Windows へのバインドからダウンロードできます。独自の上にアプリケーションを配置する場合は、次の手順を実行します。

  1. Visual Studio 2012 を起動します。

  2. メニュー バーで [ファイル][新規][プロジェクト] の順にクリックします。

    [新しいプロジェクト] ダイアログ ボックスが表示されます。

  3. [インストール済み] では、[テンプレート] のカテゴリは、[Visual Basic][Visual C#] を選択し、プロジェクトの種類の一覧の [Windows ストア] を選択します。

  4. プロジェクトの種類の一覧で、[Blue / Z] を選択します。

  5. プロジェクト [SequentialBlogReader]の名前を指定し、を [OK] のボタンをクリックします。

    ソリューション エクスプローラーに新しいプロジェクトが表示されます。

  6. [ソリューション エクスプローラー] では、MainPage.xaml のショートカット メニューを開き、[開く] を選択します。

  7. MainPage.xaml の [XAML] のペインで、次のコードに置き換えます。

    <Page
        x:Class="SequentialBlogReader.MainPage"
        xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="using:AsTaskWhenAnyDemo"
        xmlns:d="https://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="https://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d">
    
        <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
            <Button x:Name="StartButton" Content="Start" HorizontalAlignment="Stretch" Margin="325,128,330,0" VerticalAlignment="Top" Click="StartButton_Click" Height="71" Background="#FFA89B9B" FontWeight="Bold" FontSize="36"/>
            <TextBox x:Name="ResultsTextBox" Margin="325,222,330,0" TextWrapping="Wrap" VerticalAlignment="Top" Height="546" FontSize="10" ScrollViewer.VerticalScrollBarVisibility="Visible" />
        </Grid>
    </Page>
    

    テキスト ボックスとボタンを含む単純なウィンドウは、MainPage.xaml の [デザイン] のペインに表示されます。

    ユーザーが UI で行うことができる拡張機能とさまざまなアップグレードの詳細については、" "を参照してください。ブログ リーダーを作成します。

  8. [ソリューション エクスプローラー] では、MainPage.xaml.cs のショートカット メニューを開き、[コードの表示] を選択します。

  9. 次のコードで MainPage.xaml.cs のコードに置き換えます。

    ' Add an Imports statement for SyndicationClient.
    Imports Windows.Web.Syndication
    
    
    ' The Blank Page item template is documented at http:'go.microsoft.com/fwlink/?LinkId=234238
    
    Public NotInheritable Class MainPage
        Inherits Page
    
        Protected Overrides Sub OnNavigatedTo(e As Navigation.NavigationEventArgs)
    
        End Sub
    
    
        ' The async modifier enables you to use await in the event handler.
        Private Async Sub StartButton_Click(sender As Object, e As RoutedEventArgs)
            ResultsTextBox.Text = ""
    
            ' Disable the button until the operation is complete.
            StartButton.IsEnabled = False
    
            Dim client As Windows.Web.Syndication.SyndicationClient = New SyndicationClient()
    
            ' Force the SyndicationClient to download the information.
            client.BypassCacheOnRetrieve = True
    
            Dim uriList = CreateUriList()
    
            Try
                Dim feedsQuery As IEnumerable(Of IAsyncOperationWithProgress(Of SyndicationFeed, 
                                                                                RetrievalProgress)) =
                                                                From uri In uriList
                                                                Select client.RetrieveFeedAsync(uri)
    
                ' Run the query to start all the asynchronous processes.
                Dim blogFeedOpsList As List(Of IAsyncOperationWithProgress(Of SyndicationFeed, 
                                                                           RetrievalProgress)) =
                                                               feedsQuery.ToList()
    
                Dim feed As SyndicationFeed
                For Each blogFeedOp In blogFeedOpsList
                    ' The Await operator retrieves the final result (a SyndicationFeed instance)
                    ' from each IAsyncOperation instance.
                    feed = Await blogFeedOp
                    DisplayResults(feed)
                Next
    
            Catch ex As Exception
                ResultsTextBox.Text =
                    "Page could not be loaded." & vbCrLf & "Exception: " & ex.ToString()
            End Try
    
            ' Reenable the button in case you want to run the operation again.
            StartButton.IsEnabled = True
        End Sub
    
    
        Function CreateUriList() As List(Of Uri)
    
            ' Create a list of URIs.
            Dim uriList = New List(Of Uri) From
            {
                    New Uri("https://windowsteamblog.com/windows/b/developers/atom.aspx"),
                    New Uri("https://windowsteamblog.com/windows/b/extremewindows/atom.aspx"),
                    New Uri("https://windowsteamblog.com/windows/b/bloggingwindows/atom.aspx"),
                    New Uri("https://windowsteamblog.com/windows/b/springboard/atom.aspx")
            }
            Return uriList
        End Function
    
    
        Sub DisplayResults(sf As SyndicationFeed)
    
            ' Title of the blog.
            ResultsTextBox.Text &= sf.Title.Text & vbCrLf
    
            ' Titles and dates for blog posts.
            For Each item As SyndicationItem In sf.Items
    
                ResultsTextBox.Text &= vbTab & item.Title.Text & ", " &
                                    item.PublishedDate.ToString() & vbCrLf
            Next
    
            ResultsTextBox.Text &= vbCrLf
        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 a using directive for SyndicationClient.
    using Windows.Web.Syndication;
    
    
    namespace SequentialBlogReader
    {
        public sealed partial class MainPage : Page
        {
            public MainPage()
            {
                this.InitializeComponent();
            }
    
            protected override void OnNavigatedTo(NavigationEventArgs e)
            {
            }
    
    
            private async void StartButton_Click(object sender, RoutedEventArgs e)
            {
                ResultsTextBox.Text = "";
    
                // Disable the button until the operation is complete.
                StartButton.IsEnabled = false;
    
                Windows.Web.Syndication.SyndicationClient client = new SyndicationClient();
    
                // Force the SyndicationClient to download the information.
                client.BypassCacheOnRetrieve = true;
    
                var uriList = CreateUriList();
    
                try
                {
                    IEnumerable<IAsyncOperationWithProgress<SyndicationFeed, 
                        RetrievalProgress>> feedsQuery = from uri in uriList
                                                         select client.RetrieveFeedAsync(uri);
    
                    // Run the query to start all the asynchronous processes.
                    List<IAsyncOperationWithProgress<SyndicationFeed, 
                        RetrievalProgress>> blogFeedOpsList = feedsQuery.ToList();
    
                    SyndicationFeed feed;
                    foreach (var blogFeedOp in blogFeedOpsList)
                    {
                        // The await operator retrieves the final result (a SyndicationFeed instance)
                        // from each IAsyncOperation instance.
                        feed = await blogFeedOp;
                        DisplayResults(feed);
                    }
                }
                catch (Exception ex)
                {
                    ResultsTextBox.Text =
                        "Page could not be loaded.\n\r" + "Exception: " + ex.ToString();
                }
    
                // Reenable the button in case you want to run the operation again.
                StartButton.IsEnabled = true;
            }
    
            List<Uri> CreateUriList()
            {
                // Create a list of URIs.
                List<Uri> uriList = new List<Uri> 
                { 
                    new Uri("https://windowsteamblog.com/windows/b/developers/atom.aspx"),
                    new Uri("https://windowsteamblog.com/windows/b/extremewindows/atom.aspx"),
                    new Uri("https://windowsteamblog.com/windows/b/bloggingwindows/atom.aspx"),
                    new Uri("https://windowsteamblog.com/windows/b/springboard/atom.aspx")
                };
                return uriList;
            }
    
    
            void DisplayResults(SyndicationFeed sf)
            {
                // Title of the blog.
                ResultsTextBox.Text += sf.Title.Text + "\r\n";
    
                // Titles and dates for blog posts.
                foreach (SyndicationItem item in sf.Items)
                {
                    ResultsTextBox.Text += "\t" + item.Title.Text + ", " +
                                        item.PublishedDate.ToString() + "\r\n";
                }
                ResultsTextBox.Text += "\r\n";
            }
        }
    }
    
  10. プログラムを実行するには、F5 キーを選択し、を [開始] のボタンをクリックします。

完成したアプリケーションをビルド

このトピックの例は、単一の例: .NET から Windows へのバインドからダウンロードできます。独自の上にアプリケーションを配置する場合は、次の手順を実行します。

  1. Visual Studio 2012 を起動します。

  2. メニュー バーで [ファイル][新規][プロジェクト] の順にクリックします。

    [新しいプロジェクト] ダイアログ ボックスが表示されます。

  3. [インストール済み] では、[テンプレート] のカテゴリは、[Visual Basic][Visual C#] を選択し、[Windows ストア] を選択します。

  4. プロジェクトの種類の一覧から、[Blue / Z] を選択します。

  5. プロジェクト [WhenAnyBlogReader]の名前を指定し、を [OK] のボタンをクリックします。

    ソリューション エクスプローラーに新しいプロジェクトが表示されます。

  6. [ソリューション エクスプローラー] では、MainPage.xaml のショートカット メニューを開き、[開く] を選択します。

  7. MainPage.xaml の [XAML] のペインで、次のコードに置き換えます。

    <Page
        x:Class="WhenAnyBlogReader.MainPage"
        xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="using:AsTaskWhenAnyDemo"
        xmlns:d="https://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="https://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d">
    
        <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
            <Button x:Name="StartButton" Content="Start" HorizontalAlignment="Stretch" Margin="325,128,330,0" VerticalAlignment="Top" Click="StartButton_Click" Height="71" Background="#FFA89B9B" FontWeight="Bold" FontSize="36"/>
            <TextBox x:Name="ResultsTextBox" Margin="325,222,330,0" TextWrapping="Wrap" VerticalAlignment="Top" Height="546" FontSize="10" ScrollViewer.VerticalScrollBarVisibility="Visible" />
        </Grid>
    </Page>
    

    テキスト ボックスとボタンを含む単純なウィンドウは、MainPage.xaml の [デザイン] のペインに表示されます。

    アプリケーションに行うことができる拡張子とさまざまなアップグレードの詳細については、" "を参照してください。ブログ リーダーを作成します。

  8. [ソリューション エクスプローラー] では、MainPage.xaml.cs のショートカット メニューを開き、[コードの表示] を選択します。

  9. 次のコードで MainPage.xaml.cs のコードに置き換えます。

    ' Add an Imports statement for SyndicationClient.
    Imports Windows.Web.Syndication
    
    ' Add an Imports statement for the Tasks.
    Imports System.Threading.Tasks
    
    ' The Blank Page item template is documented at http:'go.microsoft.com/fwlink/?LinkId=234238
    
    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)
    
            ResultsTextBox.Text = ""
    
            ' Disable the button until the operation is complete.
            StartButton.IsEnabled = False
    
            Dim client As Windows.Web.Syndication.SyndicationClient = New SyndicationClient()
    
            ' Force the SyndicationClient to download the information.
            client.BypassCacheOnRetrieve = True
    
            Dim uriList = CreateUriList()
    
            ' The following code avoids the use of implicit typing so that you 
            ' can see the types clearly.
    
            Try
                Dim feedsQuery As IEnumerable(Of Task(Of SyndicationFeed)) =
                    From uri In uriList
                    Select client.RetrieveFeedAsync(uri).AsTask()
                ' AsTask changes the returns from RetrieveFeedAsync into tasks.
    
                ' Run the query to start all the asynchronous processes.
                Dim blogFeedTasksList As List(Of Task(Of SyndicationFeed)) = feedsQuery.ToList()
    
                Dim feed As SyndicationFeed
    
                ' Repeat the following until there are no tasks left:
                '    - Grab the first one that finishes.
                '    - Retrieve the results from the task (what the return statement 
                '      in RetrieveFeedAsync returns).
                '    - Remove the task from the list.
                '    - Display the results.
                While blogFeedTasksList.Count > 0
                    Dim nextTask As Task(Of SyndicationFeed) = Await Task.WhenAny(blogFeedTasksList)
                    feed = Await nextTask
                    blogFeedTasksList.Remove(nextTask)
                    DisplayResults(feed)
                End While
    
            Catch ex As Exception
                ResultsTextBox.Text =
                    "Page could not be loaded." & vbCrLf & "Exception: " & ex.ToString()
            End Try
    
            ' Reenable the button in case you want to run the operation again.
            StartButton.IsEnabled = True
        End Sub
    
    
        Function CreateUriList() As List(Of Uri)
    
            ' Create a list of URIs.
            Dim uriList = New List(Of Uri) From
            {
                    New Uri("https://windowsteamblog.com/windows/b/developers/atom.aspx"),
                    New Uri("https://windowsteamblog.com/windows/b/extremewindows/atom.aspx"),
                    New Uri("https://windowsteamblog.com/windows/b/bloggingwindows/atom.aspx"),
                    New Uri("https://windowsteamblog.com/windows/b/springboard/atom.aspx")
            }
            Return uriList
        End Function
    
    
        Sub DisplayResults(sf As SyndicationFeed)
    
            ' Title of the blog.
            ResultsTextBox.Text &= sf.Title.Text & vbCrLf
    
            ' Titles and dates for blog posts.
            For Each item As SyndicationItem In sf.Items
    
                ResultsTextBox.Text &= vbTab & item.Title.Text & ", " &
                                    item.PublishedDate.ToString() & vbCrLf
            Next
    
            ResultsTextBox.Text &= vbCrLf
        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 a using directive for SyndicationClient.
    using Windows.Web.Syndication;
    
    // Add a using directive for the Tasks.
    using System.Threading.Tasks;
    
    
    namespace WhenAnyBlogReader
    {
        public sealed partial class MainPage : Page
        {
            public MainPage()
            {
                this.InitializeComponent();
            }
    
            protected override void OnNavigatedTo(NavigationEventArgs e)
            {
            }
    
    
            private async void StartButton_Click(object sender, RoutedEventArgs e)
            {
                ResultsTextBox.Text = "";
    
                // Disable the button until the operation is complete.
                StartButton.IsEnabled = false;
    
                Windows.Web.Syndication.SyndicationClient client = new SyndicationClient();
    
                // Force the SyndicationClient to download the information.
                client.BypassCacheOnRetrieve = true;
    
                var uriList = CreateUriList();
    
                // The following code avoids the use of implicit typing (var) so that you 
                // can identify the types clearly.
    
                try
                {
                    IEnumerable<Task<SyndicationFeed>> feedsQuery =
                            from uri in uriList
                            // AsTask changes the returns from RetrieveFeedAsync into tasks.
                            select client.RetrieveFeedAsync(uri).AsTask();
    
                    // Run the query to start all the asynchronous processes.
                    List<Task<SyndicationFeed>> blogFeedTasksList = feedsQuery.ToList();
    
                    SyndicationFeed feed;
    
                    // Repeat the following until no tasks remain:
                    //    - Grab the first one that finishes.
                    //    - Retrieve the results from the task (what the return statement 
                    //      in RetrieveFeedAsync returns).
                    //    - Remove the task from the list.
                    //    - Display the results.
                    while (blogFeedTasksList.Count > 0)
                    {
                        Task<SyndicationFeed> nextTask = await Task.WhenAny(blogFeedTasksList);
                        feed = await nextTask;                    
                        blogFeedTasksList.Remove(nextTask);
                        DisplayResults(feed);
                    }
                }
                catch (Exception ex)
                {
                    ResultsTextBox.Text =
                        "Page could not be loaded.\n\r" + "Exception: " + ex.ToString();
                }
    
                // Reenable the button in case you want to run the operation again.
                StartButton.IsEnabled = true;
            }
    
    
            List<Uri> CreateUriList()
            {
                // Create a list of URIs.
                List<Uri> uriList = new List<Uri> 
                { 
                    new Uri("https://windowsteamblog.com/windows/b/developers/atom.aspx"),
                    new Uri("https://windowsteamblog.com/windows/b/extremewindows/atom.aspx"),
                    new Uri("https://windowsteamblog.com/windows/b/bloggingwindows/atom.aspx"),
                    new Uri("https://windowsteamblog.com/windows/b/springboard/atom.aspx")
                };
                return uriList;
            }
    
    
            void DisplayResults(SyndicationFeed sf)
            {
                // Title of the blog.
                ResultsTextBox.Text += sf.Title.Text + "\r\n";
    
                // Titles and dates for blog posts.
                foreach (SyndicationItem item in sf.Items)
                {
                    ResultsTextBox.Text += "\t" + item.Title.Text + ", " +
                                        item.PublishedDate.ToString() + "\r\n";
                }
                ResultsTextBox.Text += "\r\n";
            }
        }
    }
    
  10. プログラムを実行するには、F5 キーを選択し、を [開始] のボタンをクリックします。

参照

関連項目

WhenAny

AsTask

概念

Async および Await を使用した非同期プログラミング (C# および Visual Basic)

完了後の残りのタスクのキャンセル (C# および Visual Basic)

完了時での複数のタスクとプロセスの実行 (C# および Visual Basic)

その他の技術情報

Quickstart: 非同期プログラミングの予想の演算子を使用する

ブログ リーダーを作成します。

IAsyncOperationWithProgress