C++ における Windows ストア アプリ用の非同期操作の作成
このドキュメントでは、同時実行ランタイムを使用して Windows ストア アプリケーションの非同期操作を生成する場合に注意する重要な点について説明します。
非同期プログラミングを使用するとアプリケーションはユーザー入力への応答性を保つことができるため、これは Windows ストア アプリケーション モデルの重要なコンポーネントです。 UI スレッドをブロックすることなく、長時間実行されるタスクを開始することができ、後でタスクの結果を受け取ることができます。 また、タスクを取り消したり、タスクがバックグラウンドで実行される間に進行状況の通知を受け取ることができます。 「C++ での非同期プログラミング」のドキュメントでは、Windows ストア アプリケーションを作成するために Visual C++ で使える非同期パターンの概要について説明しています。 このドキュメントでは、Windows ランタイム の非同期操作のチェーンの使用と作成の両方の方法を解説しています。 このセクションでは、同時実行ランタイムを使用して、Windows ランタイム の別のコンポーネントで使用できる非同期操作を生成する方法、および非同期処理を実行する方法を制御する方法を説明します。 また、C++ および XAML を使用した Windows ストア アプリケーションである Hilo で、同時実行ランタイムを使用して非同期操作を実行する方法については、「Hilo での非同期プログラミング パターンとヒント (C++ と XAML を使った Windows ストア アプリ)」を参照してください。
注意
Windows ストア アプリケーションでは並列パターン ライブラリ (PPL) および非同期エージェント ライブラリを使用できます。ただし、タスク スケジューラとリソース マネージャーを使用することはできません。このドキュメントでは、同時実行ランタイムが提供する追加機能で、Windows ストア アプリケーションのみで使用でき、デスクトップ アプリケーションでは使用できないものについて説明します。
主要なポイント
他のコンポーネントで使用する非同期操作 (C++ 以外の言語で記述される場合があります) を作成するには、concurrency::create_async を使用します。
非同期操作を呼び出すコンポーネントに進行状況の通知をレポートするためには、concurrency::progress_reporter を使用します。
内部非同期操作の取り消しを可能にするには、キャンセル トークンを使用します。
create_async の関数の動作は、渡される処理関数の戻り値の型によって異なります。 タスク (task<T> または task<void>) を返す処理関数は、create_async を呼び出したコンテキストで同期的に実行されます。 T または void を返す処理関数は、任意のコンテキストで実行されます。
concurrency::task::then メソッドを使用すると、順次実行タスクのチェーンを作成できます。 Windows ストア アプリケーションでは、タスクの継続の既定のコンテキストはそのタスクが構築された方法によって異なります。 非同期アクションをタスク コンストラクターに渡すことによってタスクが作成されている場合、または非同期アクションを返すラムダ式を渡すことによってタスクが作成されている場合は、そのタスクのすべての継続の既定のコンテキストは、現在のコンテキストです。 タスクが非同期のアクションから構築されていない場合、既定ではタスクの継続には任意のコンテキストが使用されます。 既定のコンテキストを concurrency::task_continuation_context クラスで上書きできます。
目次
非同期操作を作成する
例: C++ での Windows ランタイム コンポーネントの作成
実行スレッドを制御する
例: C++ および XAML を使用した Windows ストア アプリでの実行の制御
非同期操作を作成する
並列パターン ライブラリ (PPL) でタスクや継続のモデルを使用して、バックグラウンド タスクを定義したり、前のタスクが完了すると実行される追加のタスクを定義することができます。 この機能は concurrency::task クラスによって提供されます。 このモデルの詳細および task クラスの詳細については、「タスクの並列化 (同時実行ランタイム)」を参照してください。
Windows ランタイム は、特別なオペレーティング システムの環境でのみ動作する Windows ストア アプリの作成に使用するプログラミング インターフェイスです。 このようなアプリは承認済みの関数、データ型、およびデバイスを使用し、Windows ストア から配布されます。 Windows ランタイム は、アプリケーション バイナリ インターフェイス (ABI) によって表されます。 ABI は、Windows ランタイム API を Visual C++ などのプログラミング言語で使用できるようにするための基になるバイナリ コントラクトです。
Windows ランタイム を使用すると、さまざまなプログラミング言語の最適な機能を使用して、それを 1 つのアプリケーションにまとめることができます。 たとえば、JavaScript で UI を作成し、C ++ のコンポーネントで計算量が非常に多い演算を行うことができます。 計算量が非常に多い演算をバックグラウンドで行うことができるのは、UI の応答性を保つための重要な要素です。 task クラスは C++ 固有であるため、Windows ランタイム インターフェイスを使って、他のコンポーネント (C++ 以外の言語でも記述できます) と非同期操作で通信する必要があります。 Windows ランタイム には、非同期操作を表すために使用できる 4 種類のインターフェイスが用意されています。
Windows::Foundation::IAsyncAction
非同期アクションを表します。Windows::Foundation::IAsyncActionWithProgress<TProgress>
進行状況を報告する非同期アクションを表します。Windows::Foundation::IAsyncOperation<TResult>
結果を返す非同期操作を表します。Windows::Foundation::IAsyncOperationWithProgress<TResult, TProgress>
結果を返し、進行状況を報告する、非同期操作を表します。
アクションの概念は、非同期タスクが値を生成しないことを意味します (void を返す関数を考えてみてください)。 操作 の概念は、非同期タスクが値を生成することを意味します。 進行状況 の概念は、タスクが呼び出し元に進行状況を報告できることを意味します。 JavaScript、.NET Framework および Visual C++ はそれぞれ、ABI の境界を越えて使用するため、これらのインターフェイスのインスタンスを作成する独自の方法を提供します。 Visual C++ では、同時実行ランタイムは concurrency::create_async 関数を提供します。 この関数は、Windows ランタイム の非同期アクションまたはタスクの完了を表す操作を作成します。 create_async 関数は、処理関数 (通常はラムダ式) を受け取り、内部的に task オブジェクトを作成し、4 種類の非同期 Windows ランタイム インターフェイスの 1 つでそのタスクをラップします。
注意
別の言語または別の create_async のコンポーネントからアクセスできる機能を作成する必要がある場合にのみ、Windows ランタイム を使用します。同じコンポーネントの C++ コードで操作が生成、実行されることがわかっている場合には、task クラスを直接使用します。
create_async の戻り値の型は、引数の型によって決まります。 たとえば、作業関数が値を返さず、進行状況を報告しない場合、create_async は IAsyncAction を返します。 作業関数が値を返さず、進行状況を報告する場合、create_async は IAsyncActionWithProgress を返します。 進行状況を報告するには、作業関数のパラメーターとして concurrency::progress_reporter オブジェクトを提供します。 進行状況を報告する機能により、実行された作業量と残りの作業量を報告できます (たとえば、パーセントにより)。 結果が使用できるようになったらそれを報告することができます。
IAsyncAction、IAsyncActionWithProgress<TProgress>、IAsyncOperation<TResult>、および IAsyncActionOperationWithProgress<TProgress, TProgress> インターフェイスはそれぞれ、非同期操作を取り消すことができるように Cancel メソッドを提供しています。 task クラスは、キャンセル トークンを使用します。 作業を取り消すためにキャンセル トークンを使用すると、ランタイムはそのトークンをサブスクライブする新しい作業を開始しません。 既にアクティブである作業はそのキャンセル トークンを監視でき、可能な場合には停止できます。 この機構については、ドキュメント「PPL における取り消し処理」で詳しく説明します。 Windows ランタイム Cancel メソッドを使用してタスクの取り消しをつなげる方法は 2 つあります。 最初に、create_async に渡す処理関数が concurrency::cancellation_token オブジェクトとなるように定義できます。 Cancel メソッドが呼び出されると、このキャンセル トークンは取り消され、 task 呼び出しをサポートする、基になる create_async オブジェクトに、正常な取り消しの規則が適用されます。 cancellation_token オブジェクトを指定しない場合、基になる task オブジェクトが暗黙的に定義します。 処理関数の取り消しに協調的に応答する必要がある場合は cancellation_token オブジェクトを定義します。 「例: C++ および XAML を使用した Windows ストア アプリでの実行の制御」のセクションでは、カスタムの Windows ストア C++ コンポーネントを使い、C# および XAML を使用した Windows ランタイム アプリケーションで、取り消し処理を実行する方法の例を示しています。
注意
タスクの継続のチェーンでは、concurrency::is_task_cancellation_requested が を返す場合には、常に状態をクリーンアップしてから、concurrency::cancel_current_tasktrue を呼び出します。cancel_current_task を呼び出す代わりにすぐに制御を返す場合は、操作は、取り消された状態でなく、完了の状態に遷移します。
次の表では、アプリケーションの非同期操作を定義するために使用できる組み合わせを示します。
この Windows ランタイム インターフェイスを作成するには |
create_async からこの型を返す |
これらのパラメーターの型を処理関数に渡して、暗黙的なキャンセル トークンを使用する |
これらのパラメーターの型を処理関数に渡して、明示的なキャンセル トークンを使用する |
---|---|---|---|
IAsyncAction |
void または task<void> |
(なし) |
(cancellation_token) |
IAsyncActionWithProgress<TProgress> |
void または task<void> |
(progress_reporter) |
(progress_reporter, cancellation_token) |
IAsyncOperation<TResult> |
T または task<T> |
(なし) |
(cancellation_token) |
IAsyncActionOperationWithProgress<TProgress, TProgress> |
T または task<T> |
(progress_reporter) |
(progress_reporter, cancellation_token) |
task 関数に渡す処理関数から、値または create_async オブジェクトを返すことができます。 これらのバリエーションによって異なる動作になります。 値が返されたら、処理関数はバックグラウンド スレッドで実行できるように、task にラップされます。 また、基になる task は、暗黙的なキャンセル トークンを使用します。 逆に task オブジェクトを返した場合、処理関数は同期的に実行されます。 したがって task オブジェクトを返す場合は、処理関数で時間のかかる操作はすべてタスクとして実行され、アプリケーションの応答性を保てるようにします。 また、基になる task は、暗黙的なキャンセル トークンを使用しません。 したがって、cancellation_token から task オブジェクトを返す場合に取り消しをサポートする必要がある場合、create_async オブジェクトを受け取るように処理関数を定義する必要があります。
次の例では、別の IAsyncAction コンポーネントで使用できる Windows ランタイム オブジェクトを作成するさまざまな方法を示します。
// Creates an IAsyncAction object and uses an implicit cancellation token.
auto op1 = create_async([]
{
// Define work here.
});
// Creates an IAsyncAction object and uses no cancellation token.
auto op2 = create_async([]
{
return create_task([]
{
// Define work here.
});
});
// Creates an IAsyncAction object and uses an explicit cancellation token.
auto op3 = create_async([](cancellation_token ct)
{
// Define work here.
});
// Creates an IAsyncAction object that runs another task and also uses an explicit cancellation token.
auto op4 = create_async([](cancellation_token ct)
{
return create_task([ct]()
{
// Define work here.
});
});
[トップ]
例: C++ Windows ランタイム コンポーネントを作成して C# から使用する
XAML と C# を使って UI を定義し、C ++ Windows ランタイム コンポーネントを使って計算量が非常に多い操作を実行するアプリケーションを考えてみます。 この例では、C++ コンポーネントは特定の範囲での素数を計算します。 4 つの Windows ランタイム 非同期タスク インターフェイスの相違を説明するため、まず Visual Studio で [空のソリューション] を作成し、名前を Primes とします。 次に、ソリューションに [Windows ランタイム コンポーネント] プロジェクトを追加し、名前を PrimesLibrary とします。 生成された C++ ヘッダー ファイル (この例では Class1.h の名前を Primes.h に変更しています) に次のコードを追加します。 public の各メソッドは 4 つの非同期インターフェイスの 1 つを定義します。 値を返すメソッドは、Windows::Foundation::Collections::IVector<int> オブジェクトを返します。 進行状況を報告するメソッドは、全体の作業のうち完了した割合を定義する double の値を生成します。
#pragma once
namespace PrimesLibrary
{
public ref class Primes sealed
{
public:
Primes();
// Computes the numbers that are prime in the provided range and stores them in an internal variable.
Windows::Foundation::IAsyncAction^ ComputePrimesAsync(int first, int last);
// Computes the numbers that are prime in the provided range and stores them in an internal variable.
// This version also reports progress messages.
Windows::Foundation::IAsyncActionWithProgress<double>^ ComputePrimesWithProgressAsync(int first, int last);
// Gets the numbers that are prime in the provided range.
Windows::Foundation::IAsyncOperation<Windows::Foundation::Collections::IVector<int>^>^ GetPrimesAsync(int first, int last);
// Gets the numbers that are prime in the provided range. This version also reports progress messages.
Windows::Foundation::IAsyncOperationWithProgress<Windows::Foundation::Collections::IVector<int>^, double>^ GetPrimesWithProgressAsync(int first, int last);
};
}
注意
規則により、Windows ランタイム の非同期メソッドの名前は、通常は「Async」で終わります。
生成された C++ ソース ファイル (この例では Class1.cpp の名前を Primes.cpp に変更しています) に次のコードを追加します。 is_prime 関数は、入力が素数かどうかを判定します。 残りのメソッドは Primes クラスを実装します。 create_async への呼び出しはそれぞれ、呼び出されるメソッドと互換性のあるシグネチャを使用します。 たとえば、Primes::ComputePrimesAsync は IAsyncAction を返すため、create_async に指定された処理関数は値を返さず、パラメーターとして progress_reporter オブジェクトを受け取りません。
// PrimesLibrary.cpp
#include "pch.h"
#include "Primes.h"
#include <atomic>
#include <collection.h>
#include <ppltasks.h>
#include <concurrent_vector.h>
using namespace concurrency;
using namespace std;
using namespace Platform;
using namespace Platform::Collections;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace PrimesLibrary;
Primes::Primes()
{
}
// Determines whether the input value is prime.
bool is_prime(int n)
{
if (n < 2)
{
return false;
}
for (int i = 2; i < n; ++i)
{
if ((n % i) == 0)
{
return false;
}
}
return true;
}
// Adds the numbers that are prime in the provided range
// to the primes global variable.
IAsyncAction^ Primes::ComputePrimesAsync(int first, int last)
{
return create_async([this, first, last]
{
// Ensure that the input values are in range.
if (first < 0 || last < 0)
{
throw ref new InvalidArgumentException();
}
// Perform the computation in parallel.
parallel_for(first, last + 1, [this](int n)
{
if (is_prime(n))
{
// Perhaps store the value somewhere...
}
});
});
}
IAsyncActionWithProgress<double>^ Primes::ComputePrimesWithProgressAsync(int first, int last)
{
return create_async([first, last](progress_reporter<double> reporter)
{
// Ensure that the input values are in range.
if (first < 0 || last < 0)
{
throw ref new InvalidArgumentException();
}
// Perform the computation in parallel.
atomic<long> operation = 0;
long range = last - first + 1;
double lastPercent = 0.0;
parallel_for(first, last + 1, [&operation, range, &lastPercent, reporter](int n)
{
// Report progress message.
double progress = 100.0 * (++operation) / range;
if (progress >= lastPercent)
{
reporter.report(progress);
lastPercent += 1.0;
}
if (is_prime(n))
{
// Perhaps store the value somewhere...
}
});
reporter.report(100.0);
});
}
IAsyncOperation<IVector<int>^>^ Primes::GetPrimesAsync(int first, int last)
{
return create_async([this, first, last]() -> IVector<int>^
{
// Ensure that the input values are in range.
if (first < 0 || last < 0)
{
throw ref new InvalidArgumentException();
}
// Perform the computation in parallel.
concurrent_vector<int> primes;
parallel_for(first, last + 1, [this, &primes](int n)
{
// If the value is prime, add it to the global vector.
if (is_prime(n))
{
primes.push_back(n);
}
});
// Sort the results.
sort(begin(primes), end(primes), less<int>());
// Copy the results to an IVector object. The IVector
// interface makes collections of data available to other
// Windows Runtime components.
auto results = ref new Vector<int>();
for (int prime : primes)
{
results->Append(prime);
}
return results;
});
}
IAsyncOperationWithProgress<IVector<int>^, double>^ Primes::GetPrimesWithProgressAsync(int first, int last)
{
return create_async([this, first, last](progress_reporter<double> reporter) -> IVector<int>^
{
// Ensure that the input values are in range.
if (first < 0 || last < 0)
{
throw ref new InvalidArgumentException();
}
// Perform the computation in parallel.
concurrent_vector<int> primes;
long operation = 0;
long range = last - first + 1;
double lastPercent = 0.0;
parallel_for(first, last + 1, [&primes, &operation, range, &lastPercent, reporter](int n)
{
// Report progress message.
double progress = 100.0 * (++operation) / range;
if (progress >= lastPercent)
{
reporter.report(progress);
lastPercent += 1.0;
}
// If the value is prime, add it to the local vector.
if (is_prime(n))
{
primes.push_back(n);
}
});
reporter.report(100.0);
// Sort the results.
sort(begin(primes), end(primes), less<int>());
// Copy the results to an IVector object. The IVector
// interface makes collections of data available to other
// Windows Runtime components.
auto results = ref new Vector<int>();
for (int prime : primes)
{
results->Append(prime);
}
return results;
});
}
各メソッドは最初に検証を行い、入力パラメーターが負数でないことを確認します。 入力値が負数の場合、メソッドは Platform::InvalidArgumentException をスローします。 エラー処理は、このセクションで後述します。
Windows ストア アプリケーションからこれらのメソッドを使用するには、Visual C# の [新しいアプリケーション (XAML)] テンプレートを使用して、Visual Studio ソリューションに 2 番目のプロジェクトを追加します。 この例では、プロジェクトの名前を Primes とします。 次に、Primes プロジェクトから PrimesLibrary プロジェクトへの参照を追加します。
MainPage.xaml に次のコードを追加します。 このコードは C++ コンポーネントを呼び出して結果を表示する UI を定義します。
<Page
x:Class="Primes.MainPage"
xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Primes"
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}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="300"/>
<ColumnDefinition Width="300"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="125"/>
<RowDefinition Height="125"/>
<RowDefinition Height="125"/>
</Grid.RowDefinitions>
<StackPanel Grid.Column="0" Grid.Row="0">
<Button Name="b1" Click="computePrimes">Compute Primes</Button>
<TextBlock Name="tb1"></TextBlock>
</StackPanel>
<StackPanel Grid.Column="1" Grid.Row="0">
<Button Name="b2" Click="computePrimesWithProgress">Compute Primes with Progress</Button>
<ProgressBar Name="pb1" HorizontalAlignment="Left" Width="100"></ProgressBar>
<TextBlock Name="tb2"></TextBlock>
</StackPanel>
<StackPanel Grid.Column="0" Grid.Row="1">
<Button Name="b3" Click="getPrimes">Get Primes</Button>
<TextBlock Name="tb3"></TextBlock>
</StackPanel>
<StackPanel Grid.Column="1" Grid.Row="1">
<Button Name="b4" Click="getPrimesWithProgress">Get Primes with Progress</Button>
<ProgressBar Name="pb4" HorizontalAlignment="Left" Width="100"></ProgressBar>
<TextBlock Name="tb4"></TextBlock>
</StackPanel>
<StackPanel Grid.Column="0" Grid.Row="2">
<Button Name="b5" Click="getPrimesHandleErrors">Get Primes and Handle Errors</Button>
<ProgressBar Name="pb5" HorizontalAlignment="Left" Width="100"></ProgressBar>
<TextBlock Name="tb5"></TextBlock>
</StackPanel>
<StackPanel Grid.Column="1" Grid.Row="2">
<Button Name="b6" Click="getPrimesCancellation">Get Primes with Cancellation</Button>
<Button Name="cancelButton" Click="cancelGetPrimes" IsEnabled="false">Cancel</Button>
<ProgressBar Name="pb6" HorizontalAlignment="Left" Width="100"></ProgressBar>
<TextBlock Name="tb6"></TextBlock>
</StackPanel>
</Grid>
</Page>
MainPage.xaml で、次のコードを MainPage クラスに追加します。 このコードは Primes オブジェクトとボタンのイベント ハンドラーを定義します。
private PrimesLibrary.Primes primesLib = new PrimesLibrary.Primes();
private async void computePrimes(object sender, RoutedEventArgs e)
{
b1.IsEnabled = false;
tb1.Text = "Working...";
var asyncAction = primesLib.ComputePrimesAsync(0, 100000);
await asyncAction;
tb1.Text = "Done";
b1.IsEnabled = true;
}
private async void computePrimesWithProgress(object sender, RoutedEventArgs e)
{
b2.IsEnabled = false;
tb2.Text = "Working...";
var asyncAction = primesLib.ComputePrimesWithProgressAsync(0, 100000);
asyncAction.Progress = new AsyncActionProgressHandler<double>((action, progress) =>
{
pb1.Value = progress;
});
await asyncAction;
tb2.Text = "Done";
b2.IsEnabled = true;
}
private async void getPrimes(object sender, RoutedEventArgs e)
{
b3.IsEnabled = false;
tb3.Text = "Working...";
var asyncOperation = primesLib.GetPrimesAsync(0, 100000);
await asyncOperation;
tb3.Text = "Found " + asyncOperation.GetResults().Count + " primes";
b3.IsEnabled = true;
}
private async void getPrimesWithProgress(object sender, RoutedEventArgs e)
{
b4.IsEnabled = false;
tb4.Text = "Working...";
var asyncOperation = primesLib.GetPrimesWithProgressAsync(0, 100000);
asyncOperation.Progress = new AsyncOperationProgressHandler<IList<int>, double>((operation, progress) =>
{
pb4.Value = progress;
});
await asyncOperation;
tb4.Text = "Found " + asyncOperation.GetResults().Count + " primes";
b4.IsEnabled = true;
}
private async void getPrimesHandleErrors(object sender, RoutedEventArgs e)
{
b5.IsEnabled = false;
tb5.Text = "Working...";
var asyncOperation = primesLib.GetPrimesWithProgressAsync(-1000, 100000);
asyncOperation.Progress = new AsyncOperationProgressHandler<IList<int>, double>((operation, progress) =>
{
pb5.Value = progress;
});
try
{
await asyncOperation;
tb5.Text = "Found " + asyncOperation.GetResults().Count + " primes";
}
catch (ArgumentException ex)
{
tb5.Text = "ERROR: " + ex.Message;
}
b5.IsEnabled = true;
}
private IAsyncOperationWithProgress<IList<int>, double> asyncCancelableOperation;
private async void getPrimesCancellation(object sender, RoutedEventArgs e)
{
b6.IsEnabled = false;
cancelButton.IsEnabled = true;
tb6.Text = "Working...";
asyncCancelableOperation = primesLib.GetPrimesWithProgressAsync(0, 200000);
asyncCancelableOperation.Progress = new AsyncOperationProgressHandler<IList<int>, double>((operation, progress) =>
{
pb6.Value = progress;
});
try
{
await asyncCancelableOperation;
tb6.Text = "Found " + asyncCancelableOperation.GetResults().Count + " primes";
}
catch (System.Threading.Tasks.TaskCanceledException)
{
tb6.Text = "Operation canceled";
}
b6.IsEnabled = true;
cancelButton.IsEnabled = false;
}
private void cancelGetPrimes(object sender, RoutedEventArgs e)
{
cancelButton.IsEnabled = false;
asyncCancelableOperation.Cancel();
}
これらのメソッドは async と await のキーワードを使用して、非同期操作が完了した後で UI を更新します。 C# および Visual Basic で使用できる非同期パターンの詳細については、「C# を使った Windows ストア アプリの非同期パターン」および「VB を使った Windows ストア アプリの非同期パターン」を参照してください。
getPrimesCancellation および cancelGetPrimes メソッドは連携して、ユーザーが操作の取り消しをできるようにします。 ユーザーが [キャンセル] ボタンを選択すると、cancelGetPrimes メソッドは IAsyncOperationWithProgress<TResult, TProgress>::Cancel を呼び出して、操作を取り消します。 基になる非同期操作を管理する同時実行ランタイムは内部的な例外をスローし、それは Windows ランタイム によってキャッチされ、取り消しが完了したことを通信します。 取り消しモデルの詳細については、「PPL における取り消し処理」を参照してください。
重要
同時実行ランタイムが操作の取り消しを正しく Windows ランタイム に報告できるようにするには、内部的な例外をキャッチしないでください。これは、すべての例外 (catch (...)) をキャッチしないことを意味します。すべての例外をキャッチする必要がある場合、例外を再スローして、Windows ランタイム が取り消し操作を完了できるようにします。
次の図は、各オプションが選択された後の Primes アプリケーションを示しています。
create_async を使って他の言語で使用される非同期タスクを作成する例については、「Bing Maps Trip Optimizer のサンプルでの C++ の使用」および「PPL を使った C++ による Windows 8 の非同期操作」を参照してください。
[トップ]
実行スレッドを制御する
Windows ランタイム は COM スレッド処理モデルを使用します。 このモデルでは、オブジェクトは、同期を扱う方法によって、異なるアパートメント内でホストされます。 スレッド セーフなオブジェクトは、マルチスレッド アパートメント (MTA) でホストされます。 1 つのスレッドによりアクセスされる必要があるオブジェクトは、シングルスレッド アパートメント (STA) でホストされます。
UI があるアプリケーションでは、ASTA (アプリケーション STA) スレッドはウィンドウ メッセージをポンプする必要があり、STA によりホストされた UI コントロールを更新できるプロセスでの唯一のスレッドです。 これにより次の 2 つの結果を生じます。 最初に、アプリケーションの応答性を保つためには、すべての CPU 負荷の高い操作および I/O 操作は ASTA のスレッドで実行しないようにします。 第 2 に、バックグラウンド スレッドからの結果は、UI を更新する ASTA にマーシャリングされる必要があります。 C ++ Windows ストア アプリケーションでは、MainPage および他の XAML ページは、すべて ATSA で実行されます。 したがって、ASTA で宣言されるタスクの継続は、既定ではその場で実行されるため、継続の本体でコントロールを直接更新できます。 ただし、タスクが別のタスクの入れ子になっている場合、入れ子のタスクのすべての継続は MTA で実行されます。 したがって、継続が実行されるコンテキストを明示的に指定するかどうかを検討する必要があります。
IAsyncOperation<TResult> など、非同期操作から作成されたタスクは、特別な意味を使用するので、スレッド処理の詳細に注意する必要はありません。 操作はバックグラウンド スレッドで実行できますが (またはスレッドにまったくサポートされない場合もあります)、継続は既定では継続の操作を開始したアパートメントでの実行を保証されています (つまり task::then を呼び出したアパートメントから実行されます)。 concurrency::task_continuation_context クラスを使用して、継続の実行コンテキストを制御できます。 これらの静的ヘルパー メソッドを使用して task_continuation_context オブジェクトを作成します。
concurrency::task_continuation_context::use_arbitrary を使用して、継続がバックグラウンド スレッドで実行されるように指定します。
concurrency::task_continuation_context::use_current を使用して、継続が task::then を呼び出したスレッドで実行されるように指定します。
task_continuation_context オブジェクトを task::then メソッドに渡して、継続の実行コンテキストを明示的に制御できます。またはタスクを別のアパートメントに渡してから task::then メソッドを呼び出して、暗黙的に実行コンテキストを制御できます。
重要
Windows ストア アプリケーションのメイン UI スレッドは STA で実行されるため、STA で作成した継続は既定では STA で実行されます。したがって、MTA に作成した継続は MTA 内で実行されます。
次のセクションでは、ディスクからファイルを読み込み、そのファイルで最もよく使われている単語を検索し、結果を UI に表示するアプリケーションを示します。 UI を更新する最後の操作は、UI スレッドで発生します。
重要
この動作は Windows ストア アプリケーションに固有です。デスクトップ アプリケーションでは、継続が実行される場所を制御できません。その代わりに、各継続が実行されるワーカー スレッドをスケジューラが選択します。
重要
STA で実行される継続の本体で concurrency::task::wait を呼び出さないでください。そうしないと、このメソッドが現在のスレッドをブロックして、アプリケーションが応答しなくなる場合があるため、ランタイムは concurrency::invalid_operation をスローします。ただし、タスク ベースの継続で継続元タスクの結果を受け取るために concurrency::task::get のメソッドを呼び出すことができます。
[トップ]
例: C++ および XAML を使用した Windows ストア アプリで実行を制御する
ディスクからファイルを読み込み、そのファイルで最もよく使われている単語を検索し、結果を UI に表示する C++ XAML アプリケーションを考えてみます。 このアプリケーションを作成するには、Visual Studio で Windows ストア [新しいアプリケーション (XAML)] プロジェクトを作成し、名前を CommonWords とします。 アプリケーション マニフェストで、[ドキュメント ライブラリ] の機能を指定して、アプリケーションがドキュメント フォルダーにアクセスできるようにします。 また、アプリケーション マニフェストの宣言セクションにテキスト (.txt) ファイルの種類を追加します。 アプリケーションの機能および宣言に関する詳細については、「アプリ パッケージと展開」を参照してください。
Grid 要素と ProgressRing 要素を含めるように、MainPage.xaml の TextBlock 要素を更新します。 ProgressRing は操作が進行中であることを示し、TextBlock は計算の結果を示します。
<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
<ProgressRing x:Name="Progress"/>
<TextBlock x:Name="Results" FontSize="16"/>
</Grid>
次の #include ステートメントを pch.h に追加します。
#include <sstream>
#include <ppltasks.h>
#include <concurrent_unordered_map.h>
次のメソッド宣言を MainPage クラス (MainPage.h) に追加します。
private:
// Splits the provided text string into individual words.
concurrency::task<std::vector<std::wstring>> MakeWordList(Platform::String^ text);
// Finds the most common words that are at least the provided minimum length.
concurrency::task<std::vector<std::pair<std::wstring, size_t>>> FindCommonWords(const std::vector<std::wstring>& words, size_t min_length, size_t count);
// Shows the most common words on the UI.
void ShowResults(const std::vector<std::pair<std::wstring, size_t>>& commonWords);
次の using ステートメントを MainPage.cpp に追加します。
using namespace concurrency;
using namespace std;
using namespace Windows::Storage;
using namespace Windows::Storage::Streams;
MainPage.cpp で、MainPage::MakeWordList、MainPage::FindCommonWords、および MainPage::ShowResults のメソッドを実装します。 MainPage::MakeWordList と MainPage::FindCommonWords は計算量が非常に多い演算操作を行います。 MainPage::ShowResults メソッドは演算の結果を UI に表示します。
// Splits the provided text string into individual words.
task<vector<wstring>> MainPage::MakeWordList(String^ text)
{
return create_task([text]() -> vector<wstring>
{
vector<wstring> words;
// Add continuous sequences of alphanumeric characters to the string vector.
wstring current_word;
for (wchar_t ch : text)
{
if (!iswalnum(ch))
{
if (current_word.length() > 0)
{
words.push_back(current_word);
current_word.clear();
}
}
else
{
current_word += ch;
}
}
return words;
});
}
// Finds the most common words that are at least the provided minimum length.
task<vector<pair<wstring, size_t>>> MainPage::FindCommonWords(const vector<wstring>& words, size_t min_length, size_t count)
{
return create_task([words, min_length, count]() -> vector<pair<wstring, size_t>>
{
typedef pair<wstring, size_t> pair;
// Counts the occurrences of each word.
concurrent_unordered_map<wstring, size_t> counts;
parallel_for_each(begin(words), end(words), [&counts, min_length](const wstring& word)
{
// Increment the count of words that are at least the minimum length.
if (word.length() >= min_length)
{
// Increment the count.
InterlockedIncrement(&counts[word]);
}
});
// Copy the contents of the map to a vector and sort the vector by the number of occurrences of each word.
vector<pair> wordvector;
copy(begin(counts), end(counts), back_inserter(wordvector));
sort(begin(wordvector), end(wordvector), [](const pair& x, const pair& y)
{
return x.second > y.second;
});
size_t size = min(wordvector.size(), count);
wordvector.erase(begin(wordvector) + size, end(wordvector));
return wordvector;
});
}
// Shows the most common words on the UI.
void MainPage::ShowResults(const vector<pair<wstring, size_t>>& commonWords)
{
wstringstream ss;
ss << "The most common words that have five or more letters are:";
for (auto commonWord : commonWords)
{
ss << endl << commonWord.first << L" (" << commonWord.second << L')';
}
// Update the UI.
Results->Text = ref new String(ss.str().c_str());
}
MainPage コンストラクターを変更し、Homer による著書 The Iliad でよく使われている単語を UI に表示する継続タスクのチェーンを作成します。 最初の 2 つの継続タスクは、テキストを個々の単語に分割し、よく使われている単語を検索します。これには時間がかかるため、バックグラウンドで実行されるように明示的に設定されています。 最後の継続タスクは UI を更新します。これは継続コンテキストを指定していないので、アパートメント スレッドの規則に従います。
MainPage::MainPage()
{
InitializeComponent();
// To run this example, save the contents of http://www.gutenberg.org/files/6130/6130-0.txt to your Documents folder.
// Name the file "The Iliad.txt" and save it under UTF-8 encoding.
// Enable the progress ring.
Progress->IsActive = true;
// Find the most common words in the book "The Iliad".
// Get the file.
create_task(KnownFolders::DocumentsLibrary->GetFileAsync("The Iliad.txt")).then([](StorageFile^ file)
{
// Read the file text.
return FileIO::ReadTextAsync(file, UnicodeEncoding::Utf8);
// By default, all continuations from a Windows Runtime async operation run on the
// thread that calls task.then. Specify use_arbitrary to run this continuation
// on a background thread.
}, task_continuation_context::use_arbitrary()).then([this](String^ file)
{
// Create a word list from the text.
return MakeWordList(file);
// By default, all continuations from a Windows Runtime async operation run on the
// thread that calls task.then. Specify use_arbitrary to run this continuation
// on a background thread.
}, task_continuation_context::use_arbitrary()).then([this](vector<wstring> words)
{
// Find the most common words.
return FindCommonWords(words, 5, 9);
// By default, all continuations from a Windows Runtime async operation run on the
// thread that calls task.then. Specify use_arbitrary to run this continuation
// on a background thread.
}, task_continuation_context::use_arbitrary()).then([this](vector<pair<wstring, size_t>> commonWords)
{
// Stop the progress ring.
Progress->IsActive = false;
// Show the results.
ShowResults(commonWords);
// We don't specify a continuation context here because we want the continuation
// to run on the STA thread.
});
}
注意
この例では、実行コンテキストを指定する方法と、継続のチェーンを構成する方法を示します。非同期操作から作成されたタスクは、既定では task::then を呼び出したアパートメントで継続を実行することを思い出してください。したがって、この例では task_continuation_context::use_arbitrary を使用して、UI が含まれていない操作をバックグラウンド スレッドで実行するように指定しています。
次の図は CommonWords アプリケーションの結果を示しています。
この例では、task をサポートする create_async オブジェクトが暗黙的なキャンセル トークンを使用しているため、取り消しをサポートできます。 タスクが協調的に取り消しに応答する必要がある場合には、cancellation_token オブジェクトを受け取るように処理関数を定義します。 PPL での取り消し処理の詳細については、「PPL における取り消し処理」を参照してください。
[トップ]