如何调用处理程序

How to call a handler?

本文关键字:处理 程序 调用 何调用      更新时间:2023-10-16

我不明白在io_context停止的情况下如何返回句柄。最小示例:

void my_class::async_get_one_scan(
std::function<void(const boost::system::error_code& ec, 
std::shared_ptr<my_chunked_packet>)> handler)
{
asio::spawn(strand_, [this, handler] (asio::yield_context yield)
{
const auto work = boost::asio::make_work_guard(io_service_);
my_chunk_buffer chunks;
while (!chunks.full()) {
std::array<uint8_t, 1000> datagram;
boost::system::error_code ec;
auto size = socket_.async_receive(asio::buffer(datagram), yield[ec]);
if (!ec)
process_datagram(datagram, size, chunks);
else {
handler(ec, nullptr);
return;
}
}
io_service_.post(std::bind(handler, boost::system::error_code, chunks.packet()));
});
}

调试asio输出:

@asio|1532525798.533266|6*7|strand@01198ff0.dispatch
@asio|1532525798.533266|>7|
@asio|1532525798.533266|>0|
@asio|1532525798.533266|0*8|socket@008e345c.async_receive
@asio|1532525798.533266|<7|
@asio|1532525798.533266|<6|
@asio|1532525799.550640|0|socket@008e34ac.close
@asio|1532525799.550640|0|socket@008e345c.close
@asio|1532525799.551616|~8|

所以最后一个async_receive() #8是在|<6|io_context.stop()被调用之后创建的,然后我不知道如何从yield_context获得error_code来调用处理程序。

问题2这是异步读取数据块以收集整个数据包的正确方式吗?

根据定义,io_context::stop阻止事件循环执行其他处理程序。因此,无法将退出代码获取到处理程序中,因为它不会被调用。

您可能想要一个"软停止"功能,停止向io_context接纳新的异步任务,并可以选择取消任何挂起的操作。

如果挂起的操作可能花费太长时间,则需要添加一个截止日期计时器,以强制在某个阈值时间间隔取消操作。

使run循环退出的常用方法是释放work对象。看见https://www.boost.org/doc/libs/1_67_0/doc/html/boost_asio/reference/io_context__work.html