我使用带有超时的 readdata=0;
port_->async_read_some(boost::asio::buffer(vector),
boost::bind(readCallback));
//init async timer
boost::asio::deadline_timer timer(io);
timer.async_wait(boost::bind(timeoutHandler));
timer.expires_from_now(boost::posix_time::seconds(5));
io.reset();
do {
io.run_one();
}
while (readdata==0);
代码
void readCallback()
{
std::cout << "READ CALLBACK: "<<x<<std::endl;
readdata=1;
return;
}
void timeoutHandler()
{
std::cout << "TIMEOUT CALLBACK: "<<x<<std::endl;
readdata=1;
}
这是我的回调
System.IO.File.ReadAllText("D:\home\site\wwwroot\Prod-Enterprise-Test-6-26-2016-credentials.publishsettings")
我的问题是timeoutHandler是立即执行的,而不是在5秒后执行
答案 0 :(得分:2)
简单的错误。在致电expires_from_now
之前,您应该async_wait
。
#include <iostream>
#include <asio.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
int main() {
asio::io_service io_s;
asio::deadline_timer timer(io_s);
timer.expires_from_now(boost::posix_time::seconds(5));
timer.async_wait([](auto err_c) { std::cout << "After 5 seconds" << std::endl; } );
io_s.reset();
io_s.run();
return 0;
}