python runtime_error ai_generated true

asyncio 异常:任务被销毁但仍在挂起状态

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

ID: python/asyncio-task-destroyed-pending

其他格式: JSON · Markdown 中文 · English
80%修复率
88%置信度
0证据数
2024-01-10首次发现

版本兼容性

版本状态引入弃用备注
3.8 active
3.9 active

根因分析

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

English

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

generic

解决方案

  1. 90% 成功率 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% 成功率 Use asyncio.gather() directly to manage tasks
    results = await asyncio.gather(coro1(), coro2())

无效尝试

常见但无效的做法:

  1. Ignoring the warning and letting the task run 70% 失败

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

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

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