提升ASIO:从处理程序异常中恢复

时间:2017-10-25 13:43:16

标签: boost-asio

如果ASIO回调引发错误,是否可以安全地恢复异步处理?

简而言之,以下代码是否有任何优点?

void runAsioLoop()
{
    boost::asio::io_service::work work(this->m_ioService);
    boost::system::error_code unused;

    while (m_running) {
        try {
            this->m_ioService.run(unused);
            this->m_ioService.reset();
        } catch (...) {
            std::cerr << "*** An error happened\n";
        }
    }
}

1 个答案:

答案 0 :(得分:1)

它应该有效,但更好的习语是:

for (;;) {
    try {
        svc.run();
        break; // exited normally
    } catch (std::exception const &e) {
        logger.log(LOG_ERR) << "[eventloop] An unexpected error occurred running a task: " << e.what();
    } catch (...) {
        logger.log(LOG_ERR) << "[eventloop] An unexpected error occurred running a task";
    }
}

以下是它的文档:http://www.boost.org/doc/libs/1_65_1/doc/html/boost_asio/reference/io_service.html#boost_asio.reference.io_service.effect_of_exceptions_thrown_from_handlers