Cara: Mengirim Pesan pada Interval Reguler

Contoh ini menunjukkan cara menggunakan kelas konkurensi::timer untuk mengirim pesan secara berkala.

Contoh

Contoh berikut menggunakan timer objek untuk melaporkan kemajuan selama operasi yang panjang. Contoh ini menautkan objek ke timerobjek konkurensi::call . Objek call mencetak indikator kemajuan ke konsol secara berkala. Metode konkurensi::timer::start menjalankan timer pada konteks terpisah. Fungsi ini perform_lengthy_operation memanggil fungsi konkurensi::tunggu pada konteks utama untuk mensimulasikan operasi yang memakan waktu.

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

Contoh ini menghasilkan contoh output berikut:

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

Mengompilasi Kode

Salin kode contoh dan tempelkan dalam proyek Visual Studio, atau tempelkan dalam file yang diberi nama report-progress.cpp lalu jalankan perintah berikut di jendela Prompt Perintah Visual Studio.

cl.exe /EHsc report-progress.cpp

Baca juga

Pustaka Agen Asinkron
Blok Pesan Asinkron
Fungsi Passing Pesan