diff --git a/src/dht_proxy_client.cpp b/src/dht_proxy_client.cpp
index 102761c5d0bf3b958697625bc12da5fc2e41f152..5e40e94b5b608bed3938e058dabcf0a63de11679 100644
--- a/src/dht_proxy_client.cpp
+++ b/src/dht_proxy_client.cpp
@@ -976,17 +976,23 @@ DhtProxyClient::restartListeners()
     for (auto& search: searches_) {
         for (auto& l: search.second.listeners) {
             auto& listener = l.second;
-            auto state = listener.state;
-            if (listener.thread.joinable()) {
+            if (auto state = listener.state)
                 state->cancel = true;
-                if (listener.req) {
-                    try {
-                        restbed::Http::close(listener.req);
-                    } catch (const std::exception& e) {
-                        DHT_LOG.w("Error closing socket: %s", e.what());
-                    }
-                    listener.req.reset();
+            if (listener.req) {
+                try {
+                    restbed::Http::close(listener.req);
+                } catch (const std::exception& e) {
+                    DHT_LOG.w("Error closing socket: %s", e.what());
                 }
+                listener.req.reset();
+            }
+        }
+    }
+    for (auto& search: searches_) {
+        for (auto& l: search.second.listeners) {
+            auto& listener = l.second;
+            auto state = listener.state;
+            if (listener.thread.joinable()) {
                 listener.thread.join();
             }
             // Redo listen