方法: メッセージを定期的に送信する

この例では、Concurrency::timer クラスを使用してメッセージを定期的に送信する方法を示します。

使用例

次の例では、timer オブジェクトを使用して、時間のかかる操作中に進行状況を報告します。 この例では、timer オブジェクトを Concurrency::call オブジェクトにリンクします。 call オブジェクトは、プログレス インジケーターをコンソールに定期的に出力します。 Concurrency::timer::start メソッドは、タイマーを独立したコンテキストで実行します。 perform_lengthy_operation 関数は、メインのコンテキストで Concurrency::wait 関数を呼び出して、時間のかかる操作をシミュレートします。

// report-progress.cpp
// compile with: /EHsc
#include <agents.h>
#include <iostream>

using namespace Concurrency;
using namespace std;

// Simulates a lengthy operation.
void perform_lengthy_operation()
{
   // Yield the current context for one second.
   wait(1000);
}

int wmain()
{  
   // Create a call object that prints a single character to the console.
   call<wchar_t> report_progress([](wchar_t c) { 
      wcout << c;
   });

   // Create a timer object that sends the dot character to the 
   // call object every 100 milliseconds.
   timer<wchar_t> progress_timer(100, L'.', &report_progress, true);

   wcout << L"Performing a lengthy operation";

   // Start the timer on a separate context.
   progress_timer.start();

   // Perform a lengthy operation on the main context.
   perform_lengthy_operation();

   // Stop the timer and print a message.
   progress_timer.stop();

   wcout << L"done.";
}

この例では、次のサンプル出力が生成されます。

Performing a lengthy operation..........done.

コードのコンパイル

プログラム例をコピーし、Visual Studio プロジェクトに貼り付けるか、report-progress.cpp という名前のファイルに貼り付け、Visual Studio 2010 のコマンド プロンプト ウィンドウで次のコマンドを実行します。

cl.exe /EHsc report-progress.cpp

参照

参照

timer クラス

概念

非同期エージェント ライブラリ

非同期メッセージ ブロック

メッセージ パッシング関数