如何:定期发送消息

本示例说明如何使用 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 类

概念

异步代理库

异步消息块

消息传递函数