Skip to content

Commit 921b47e

Browse files
authored
keep a reference to asyncio tasks (#1982)
1 parent bc248e8 commit 921b47e

File tree

2 files changed

+6
-2
lines changed

2 files changed

+6
-2
lines changed

can/notifier.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,7 @@ def __init__(
148148
self._lock = threading.Lock()
149149

150150
self._readers: list[Union[int, threading.Thread]] = []
151+
self._tasks: set[asyncio.Task] = set()
151152
_bus_list: list[BusABC] = bus if isinstance(bus, list) else [bus]
152153
for each_bus in _bus_list:
153154
self.add_bus(each_bus)
@@ -256,8 +257,10 @@ def _on_message_received(self, msg: Message) -> None:
256257
for callback in self.listeners:
257258
res = callback(msg)
258259
if res and self._loop and asyncio.iscoroutine(res):
259-
# Schedule coroutine
260-
self._loop.create_task(res)
260+
# Schedule coroutine and keep a reference to the task
261+
task = self._loop.create_task(res)
262+
self._tasks.add(task)
263+
task.add_done_callback(self._tasks.discard)
261264

262265
def _on_error(self, exc: Exception) -> bool:
263266
"""Calls ``on_error()`` for all listeners if they implement it.

doc/changelog.d/1938.fixed.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Keep a reference to asyncio tasks in `can.Notifier` as recommended by [python documentation](https://docs.python.org/3/library/asyncio-task.html#asyncio.create_task).

0 commit comments

Comments
 (0)