gpt4 book ai didi

c++ - boost::asio::deadline_timer cancel() 方法未调用计时器处理程序

转载 作者:太空宇宙 更新时间:2023-11-04 12:32:56 25 4
gpt4 key购买 nike

boost 1.69

嗨。我正在尝试创建一个类来执行 https 请求,但也有错误检查超时。

我正在为 https 使用 boost beast 函数(工作正常)并且我正在使用 deadline_timer 类来设置计时器

我将 https 请求和计时器设置为在相同的 IO_context 上运行。这个想法是,如果发生超时,我想抛出错误并停止执行 IO 上下文,或者如果 https 正常工作,我想停止计时器。

我正在尝试使用 cancel() 方法来停止计时器并根据文档状态调用超时句柄

This function forces the completion of any pending asynchronous wait operations against the timer. The handler for each cancelled operation will be invoked with the boost::asio::error::operation_aborted error code

但是定时器处理程序永远不会被调用。如何在取消定时器时调用定时器处理程序?

这是一些代码:

    /* Set up timeout timer and start it */
boost::asio::deadline_timer timer{query->ioc,boost::posix_time::seconds(TIMEOUT_HTTPS)};
timer.async_wait(std::bind(&HttpsCom::on_timeout, this, std::placeholders::_1, query));

// Look up the domain name
std::cout << "Making the request..." << std::endl;
tcp::resolver resolver{query->ioc};
resolver.async_resolve(host, port, std::bind(&HttpsCom::on_resolve,this,std::placeholders::_1,std::placeholders::_2, query));

query->ioc.run();

if (latestError == HTTPS_SUCCESS){
std::size_t test = timer.cancel();
std::cout << test << std::endl; // Timer gets cancel as test = 1
}

这是我的定时器处理程序

void HttpsCom::on_timeout(const boost::system::error_code& ec, std::shared_ptr<HTTPSQueryStruct_t> query){
std::cout << "Timeout" << std::endl;
}

这是我的关闭处理程序(HTTPS 成功)

void HttpsCom::on_shutdown(boost::system::error_code ec, std::shared_ptr<HTTPSQueryStruct_t> query){
std::cout << "on_shutdown()" << std::endl;

// boost::ignore_unused(ec);
std::cerr << "on_shutdown" << ": " << ec.message() << std::endl;

/* If we get here the connection was closed gracefully */
setLatestErrorCode(HTTPS_SUCCESS);
query->ioc.stop();
}

最佳答案

我发现了问题。似乎停止 ioc 只是删除或以某种方式忘记了排队的处理程序。因此,当在停止 ioc 后调用 timer.cancel() 函数时,您不会去任何地方,因为它已经忘记了处理程序。

关于c++ - boost::asio::deadline_timer cancel() 方法未调用计时器处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57929338/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com