chore: improve ws shutdown

This commit is contained in:
Matthias
2026-04-23 20:51:38 +02:00
parent a625cbecff
commit cdc01122d5
+12 -9
View File
@@ -1,6 +1,5 @@
import asyncio import asyncio
import logging import logging
import time
from copy import deepcopy from copy import deepcopy
from functools import partial from functools import partial
from threading import Thread from threading import Thread
@@ -37,8 +36,15 @@ class ExchangeWS:
try: try:
self._loop.run_forever() self._loop.run_forever()
finally: finally:
if self._loop.is_running(): if not self._loop.is_closed():
self._loop.stop() # Cancel remaining tasks and close the loop in the owning thread.
pending = asyncio.all_tasks(self._loop)
for task in pending:
task.cancel()
if pending:
self._loop.run_until_complete(asyncio.gather(*pending, return_exceptions=True))
self._loop.run_until_complete(self._loop.shutdown_asyncgens())
self._loop.close()
def cleanup(self) -> None: def cleanup(self) -> None:
logger.debug("Cleanup called - stopping") logger.debug("Cleanup called - stopping")
@@ -47,13 +53,10 @@ class ExchangeWS:
task.cancel() task.cancel()
if hasattr(self, "_loop") and not self._loop.is_closed(): if hasattr(self, "_loop") and not self._loop.is_closed():
self.reset_connections() self.reset_connections()
self._loop.call_soon_threadsafe(self._loop.stop) self._loop.call_soon_threadsafe(self._loop.stop)
time.sleep(0.1) self._thread.join(timeout=5)
if not self._loop.is_closed(): if self._thread.is_alive():
self._loop.close() logger.warning("Websocket loop thread did not stop within timeout.")
self._thread.join()
logger.debug("Stopped") logger.debug("Stopped")
def reset_connections(self) -> None: def reset_connections(self) -> None: