Improved set_timeout(): no longer keeps connection alive longer than necessary.

This commit is contained in:
eidheim 2019-05-27 21:13:28 +02:00
commit 514a135e0c
2 changed files with 12 additions and 8 deletions

View file

@ -100,11 +100,13 @@ namespace SimpleWeb {
return; return;
} }
timer = std::unique_ptr<asio::steady_timer>(new asio::steady_timer(get_socket_executor(*socket), std::chrono::seconds(seconds))); timer = std::unique_ptr<asio::steady_timer>(new asio::steady_timer(get_socket_executor(*socket), std::chrono::seconds(seconds)));
auto self = this->shared_from_this(); std::weak_ptr<Connection> self_weak(this->shared_from_this()); // To avoid keeping Connection instance alive longer than needed
timer->async_wait([self](const error_code &ec) { timer->async_wait([self_weak](const error_code &ec) {
if(!ec) { if(!ec) {
error_code ec; if(auto self = self_weak.lock()) {
self->socket->lowest_layer().cancel(ec); error_code ec;
self->socket->lowest_layer().cancel(ec);
}
} }
}); });
} }

View file

@ -277,10 +277,12 @@ namespace SimpleWeb {
} }
timer = std::unique_ptr<asio::steady_timer>(new asio::steady_timer(get_socket_executor(*socket), std::chrono::seconds(seconds))); timer = std::unique_ptr<asio::steady_timer>(new asio::steady_timer(get_socket_executor(*socket), std::chrono::seconds(seconds)));
auto self = this->shared_from_this(); std::weak_ptr<Connection> self_weak(this->shared_from_this()); // To avoid keeping Connection instance alive longer than needed
timer->async_wait([self](const error_code &ec) { timer->async_wait([self_weak](const error_code &ec) {
if(!ec) if(!ec) {
self->close(); if(auto self = self_weak.lock())
self->close();
}
}); });
} }