Boost Asio async_wait触发Operation canceled错误,无限循环失效
Boost Asio steady_timer无限循环触发失败:Operation canceled 问题解决
问题根源
你的代码中steady_timer timer是waitForTimer函数的局部变量,函数执行完毕后定时器对象会被立即销毁。而async_wait是异步操作,函数返回时异步等待还未完成,定时器销毁会自动取消未完成的异步操作,导致回调收到Operation canceled错误,无法进入下一次循环。
解决方案1:用智能指针管理定时器生命周期
通过std::shared_ptr延长定时器的生命周期,确保回调执行完成前对象不会被销毁:
#include <iostream> #include <boost/asio.hpp> #include <memory> void waitForTimer(boost::asio::io_context& ioContext) { // 用shared_ptr托管定时器,避免函数结束后立即销毁 auto timer = std::make_shared<boost::asio::steady_timer>(ioContext, boost::asio::chrono::seconds(1)); timer->async_wait([&, timer](const boost::system::error_code& error) { if (!error) { std::cout << "Timer expired! Asynchronous wait complete." << std::endl; waitForTimer(ioContext); // 递归调用实现无限循环 } else { std::cerr << "Error: " << error.message() << std::endl; } }); } int main() { std::cout << "Using Boost " << BOOST_VERSION / 100000 << "." << BOOST_VERSION / 100 % 1000 << "." << BOOST_VERSION % 100 << std::endl; boost::asio::io_context ioContext; waitForTimer(ioContext); ioContext.run(); return 0; }
解决方案2:复用同一个定时器(更高效)
避免每次创建新定时器,直接在回调中重置现有定时器的到期时间:
#include <iostream> #include <boost/asio.hpp> void waitHandler(const boost::system::error_code& error, boost::asio::steady_timer& timer) { if (!error) { std::cout << "Timer expired! Asynchronous wait complete." << std::endl; // 重置定时器到期时间,再次发起异步等待 timer.expires_after(boost::asio::chrono::seconds(1)); timer.async_wait([&timer](const boost::system::error_code& ec) { waitHandler(ec, timer); }); } else { std::cerr << "Error: " << error.message() << std::endl; } } int main() { std::cout << "Using Boost " << BOOST_VERSION / 100000 << "." << BOOST_VERSION / 100 % 1000 << "." << BOOST_VERSION % 100 << std::endl; boost::asio::io_context ioContext; boost::asio::steady_timer timer(ioContext, boost::asio::chrono::seconds(1)); timer.async_wait([&timer](const boost::system::error_code& ec) { waitHandler(ec, timer); }); ioContext.run(); return 0; }
内容的提问来源于stack exchange,提问作者Metropol_Tilkisi
相关产品推荐
相关产品推荐

