closing a boost::asio::ip::tcp::socket with pending connect
According to the boost asio documentation, if I call close on a socket that has an asynchronous connect operation pending, the handler will be called "immediately" with an error code. From the documentation:
This function is used to close the socket. Any asynchronous send, receive or connect operations will be cancelled immediately, and will complete with the boost::asio::error::operation_aborted error.
But the handler is not actually called immediately/synchronously, it is called asynchronously when control returns to the io_service. Is it possible that my connect handler still gets called without an error code after I call close, if the connect actually succeeded and my handler callback has already been posted to the io_service?
The documentation states that the outstanding operations will be canceled immediately, not that they will be called immediately.
It is possible that the connect operation has already completed, and the handler is queued in the io_service
for deferred invocation with its error_code
as boost::system::errc::success
. It may be worth consider checking if the socket is_open()
in the completion handler, as done in this answer. For more details on this behavior, see this answer.
The operations will be cancelled immediately, but the handler doesn't get called synchronously. If a "normal" completion handler is already in the queue when you call close()
, it definitely will be invoked, and you won't get "operation_aborted".