python-can icon indicating copy to clipboard operation
python-can copied to clipboard

Async callbacks tasks is not kept and might be GC before the callback is run

Open sveinse opened this issue 8 months ago • 1 comments

The can rx message handler in class Notifier is creating tasks when runs in async mode and gets a coroutine callback.

https://github.com/hardbyte/python-can/blob/5d62394006f42d1bf98e159fe9bb08d10e47e6eb/can/notifier.py#L143-L148

However the python docs is clear that the reference to the task needs to be kept to ensure its not garbage collected: https://docs.python.org/3/library/asyncio-task.html#asyncio.create_task

The fix should be fairly straight forward:

    def _on_message_received(self, msg: Message) -> None:
        for callback in self.listeners:
            res = callback(msg)
            if res and self._loop and asyncio.iscoroutine(res):
                # Schedule coroutine
                # In __init__: self._tasks: set[asyncio.Task] = set()
                task = self._loop.create_task(res)
                self._tasks.add(task)
                task.add_done_callback(self._tasks.discard)

sveinse avatar May 08 '25 16:05 sveinse

Looks reasonable, a PR is welcome

zariiii9003 avatar May 30 '25 14:05 zariiii9003