Please explain “Task was destroyed but it is pending!”

前端 未结 4 757
难免孤独
难免孤独 2021-02-06 22:54

Python 3.4.2

I am learning asyncio and I use it to continously listen IPC bus, while gbulb listens to the dbus.

Some side notes:

So I created a fun

4条回答
  •  暖寄归人
    2021-02-06 23:15

    I had this message and I believe it was caused by garbage collection of pending task. The Python developers were debating whether tasks created in asyncio should create strong references and decided they shouldn't (after 2 days of looking into this problem I strongly disagree! ... see the discussion here https://bugs.python.org/issue21163)

    I created this utility for myself to make strong references to tasks and automatically clean it up (still need to test it thoroughly)...

    import asyncio
    
    #create a strong reference to tasks since asyncio doesn't do this for you
    task_references = set()
    
    def register_ensure_future(coro):
        task = asyncio.ensure_future(coro)
        task_references.add(task)
    
        # Setup cleanup of strong reference on task completion...
        def _on_completion(f):
            task_references.remove(f)
        task.add_done_callback(_on_completion)
        
        return task
    

    It seems to me that tasks should have a strong reference for as long as they are active! But asyncio doesn't do that for you so you can have some bad surprises once gc happens and long hours of debugging.

提交回复
热议问题