Bewerken

Delen via


How to: Send a Message at a Regular Interval

This example shows how to use the concurrency::timer class to send a message at a regular interval.

Example

The following example uses a timer object to report progress during a lengthy operation. This example links the timer object to a concurrency::call object. The call object prints a progress indicator to the console at a regular interval. The concurrency::timer::start method runs the timer on a separate context. The perform_lengthy_operation function calls the concurrency::wait function on the main context to simulate a time-consuming operation.

// 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.";
}

This example produces the following sample output:

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

Compiling the Code

Copy the example code and paste it in a Visual Studio project, or paste it in a file that is named report-progress.cpp and then run the following command in a Visual Studio Command Prompt window.

cl.exe /EHsc report-progress.cpp

See also

Asynchronous Agents Library
Asynchronous Message Blocks
Message Passing Functions