Skip to content

Commit bb9b718

Browse files
committed
connections.pybricks: fix leaking tasks if race_disconnect() is canceled
If the `race_disconnect()` method is canceled while waiting for either of the tasks, there is nothing that ever awaits the tasks, so we get errors like: 2025-09-09 21:22:25,946: ERROR: asyncio: Task was destroyed but it is pending! task: <Task pending name='race_disconnect: Queue.get' coro=<Queue.get() done, defined at python\3.13.0\Lib\asyncio\queues.py:172> wait_for=<Future cancelled>> 2025-09-09 21:22:25,947: ERROR: asyncio: Task was destroyed but it is pending! task: <Task pending name='Task-21' coro=<Event.wait() done, defined at python\3.13.0\Lib\asyncio\locks.py:200> wait_for=<Future pending cb=[Task.task_wakeup()]>> To avoid this, cancel the tasks if anything goes wrong while waiting.
1 parent b6da663 commit bb9b718

File tree

1 file changed

+9
-4
lines changed

1 file changed

+9
-4
lines changed

pybricksdev/connections/pybricks.py

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -349,10 +349,15 @@ def handle_disconnect(state: ConnectionState):
349349
disconnect_event.set()
350350

351351
with self.connection_state_observable.subscribe(handle_disconnect):
352-
done, pending = await asyncio.wait(
353-
{awaitable_task, disconnect_task},
354-
return_when=asyncio.FIRST_COMPLETED,
355-
)
352+
try:
353+
done, pending = await asyncio.wait(
354+
{awaitable_task, disconnect_task},
355+
return_when=asyncio.FIRST_COMPLETED,
356+
)
357+
except BaseException:
358+
awaitable_task.cancel()
359+
disconnect_task.cancel()
360+
raise
356361

357362
for t in pending:
358363
t.cancel()

0 commit comments

Comments
 (0)