HOW TO:定期傳送訊息
本範例顯示如何使用 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) 輸出:
Performing a lengthy operation..........done.
編譯程式碼
將範例程式碼複製並貼上它在 Visual Studio 專案中,或將它貼在檔名為報表 progress.cpp ,然後執行下列命令,Visual Studio 的命令提示字元] 視窗中。
cl.exe /EHsc report-progress.cpp