在UI应用程序上实现计时器类。
基本上我遇到的问题是调用io.run()
会阻塞,导致async_wait
调用无用。从阅读其他帖子我得到的印象是,某种方式Timer,或者至少是调用startCountdown
的代码,应该在另一个线程上。
以下是我的代码。如何以在Boost中认为正确的方式管理它?
class Timer
{
public:
Timer() : countdownTimer(io) { }
void startCountdown(int seconds)
{
countdownTimer.expires_from_now(boost::posix_time::seconds(seconds));
countdownTimer.async_wait(boost::bind(&Timer::on_timeout, this, _1));
io.run(); // this blocks
}
void on_timeout(const boost::system::error_code& e)
{
if (e != boost::asio::error::operation_aborted) {
cout << "Timer expired!";
}
}
private:
boost::asio::io_service io;
boost::asio::deadline_timer countdownTimer;
}