如何调用处理程序
How to call a handler?
我不明白在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
相关文章:
- 获取日期异步信号安全吗?如果在信号处理程序中使用,它会导致死锁吗
- 如何在信号处理程序和普通函数中对全局变量进行互斥读写操作
- 为什么我的 IExtractIcon 处理程序没有被调用?
- 在遍历处理程序的向量时注册和注销处理程序
- 有可能在信号处理程序中设置promise吗
- 在信号处理程序中捕获C++未处理的异常并恢复应用程序
- 通过安装信号处理程序关闭多线程应用程序
- QDateTime::toString() 在退出处理程序中使用时失败
- 如何在 WindowProc 处理程序中区分箭头键和数字键盘?
- async_write完成处理程序最早何时完成?
- C++事件系统 - 多态事件和事件处理程序
- 具有shared_ptr的处理程序中的分段错误
- 为什么我的信号处理程序只执行一次?
- GTK C++:找不到信号处理程序 您是否使用 -rdynamic 进行了编译?
- 如何使用从处理程序调度的最终回调将响应异步返回给调用方on_read?
- C++ 在信号处理程序后继续执行
- wxWidgets 拖放文件事件处理程序初始化问题(无效static_cast)
- 某些 boost::asio 异步函数是否将处理程序连接到操作,以便处理程序被触发一次?
- 没有信号处理程序的POSIX定时器的目的是什么?
- 处理程序的模块列表中有一个错误的模块"WebSocketModule"