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,12 +100,14 @@ namespace SimpleWeb {
return;
}
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();
timer->async_wait([self](const error_code &ec) {
std::weak_ptr<Connection> self_weak(this->shared_from_this()); // To avoid keeping Connection instance alive longer than needed
timer->async_wait([self_weak](const error_code &ec) {
if(!ec) {
if(auto self = self_weak.lock()) {
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)));
auto self = this->shared_from_this();
timer->async_wait([self](const error_code &ec) {
if(!ec)
std::weak_ptr<Connection> self_weak(this->shared_from_this()); // To avoid keeping Connection instance alive longer than needed
timer->async_wait([self_weak](const error_code &ec) {
if(!ec) {
if(auto self = self_weak.lock())
self->close();
}
});
}