python runtime_error ai_generated true

asyncio.exceptions.CancelledError: Task was destroyed but it is pending

ID: python/asyncio-task-destroyed-pending

Also available as: JSON · Markdown · 中文
80%Fix Rate
88%Confidence
0Evidence
2024-01-10First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.8 active
3.9 active

Root Cause

A task is garbage collected while it is still pending (not completed), often due to losing a reference to the task.

generic

中文

任务在仍处于挂起状态时被垃圾回收,通常是因为丢失了对任务的引用。

Workarounds

  1. 90% success Store the task in a list or variable to keep a reference
    tasks = []
    task = asyncio.create_task(coro())
    tasks.append(task)
    await asyncio.gather(*tasks)
  2. 95% success Use asyncio.gather() directly to manage tasks
    results = await asyncio.gather(coro1(), coro2())

Dead Ends

Common approaches that don't work:

  1. Ignoring the warning and letting the task run 70% fail

    The task may be cancelled abruptly, causing incomplete operations and resource leaks.

  2. Using asyncio.ensure_future() without storing the task 60% fail

    ensure_future() returns a task, but if not stored, it may be garbage collected while pending.