fix: hold a strong reference to the AsyncEngine setup task (#1533) · python-zeroconf/python-zeroconf@d4e6f25

Original file line numberDiff line numberDiff line change

@@ -50,6 +50,7 @@ class AsyncEngine:

5050

"_cleanup_timer",

5151

"_listen_socket",

5252

"_respond_sockets",

53+

"_setup_task",

5354

"loop",

5455

"protocols",

5556

"readers",

@@ -73,6 +74,7 @@ def __init__(

7374

self._listen_socket = listen_socket

7475

self._respond_sockets = respond_sockets

7576

self._cleanup_timer: asyncio.TimerHandle | None = None

77+

self._setup_task: asyncio.Task[None] | None = None

7678
7779

def setup(

7880

self,

@@ -82,14 +84,15 @@ def setup(

8284

"""Set up the instance."""

8385

self.loop = loop

8486

self.running_future = loop.create_future()

85-

self.loop.create_task(self._async_setup(loop_thread_ready))

87+

self._setup_task = self.loop.create_task(self._async_setup(loop_thread_ready))

8688
8789

async def _async_setup(self, loop_thread_ready: threading.Event | None) -> None:

8890

"""Set up the instance."""

8991

self._async_schedule_next_cache_cleanup()

9092

await self._async_create_endpoints()

9193

assert self.running_future is not None

92-

self.running_future.set_result(True)

94+

if not self.running_future.done():

95+

self.running_future.set_result(True)

9396

if loop_thread_ready:

9497

loop_thread_ready.set()

9598

@@ -135,6 +138,8 @@ def _async_schedule_next_cache_cleanup(self) -> None:

135138
136139

async def _async_close(self) -> None:

137140

"""Cancel and wait for the cleanup task to finish."""

141+

assert self._setup_task is not None

142+

await self._setup_task

138143

self._async_shutdown()

139144

await asyncio.sleep(0) # flush out any call soons

140145

assert self._cleanup_timer is not None