共用方式為


如何:定期傳送訊息

這個範例將示範如何使用 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.";
}

這個範例 (Example) 會產生下列範例 (Sample) 輸出:

  

編譯程式碼

請複製範例程式碼,並將它貼在 Visual Studio 專案中,或貼在名為 report-progress.cpp 的檔案中,然後在 Visual Studio 的 [命令提示字元] 視窗中執行下列命令。

cl.exe /EHsc report-progress.cpp

請參閱

參考

timer 類別

概念

非同步代理程式程式庫

非同步訊息區

訊息傳遞函式