Share via


如何:定期傳送訊息

此範例示範如何使用 concurrency:: timer 類別 定期傳送訊息。

範例

下列範例會使用 timer 物件在冗長的作業期間報告進度。 這個範例會將 timer 物件連結至 並行::call 物件。 物件 call 會定期將進度指示器列印至主控台。 並行 ::timer::start 方法會在不同的內容上執行計時器。 函 perform_lengthy_operation 式會在 主要內容上呼叫並行::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 命令提示字元視窗中執行下列命令。

cl.exe /EHsc report-progress.cpp

另請參閱

非同步代理程式程式庫
非同步訊息區
訊息傳遞函式