python
runtime_error
ai_generated
true
asyncio 异常:任务被销毁但仍在挂起状态
asyncio.exceptions.CancelledError: Task was destroyed but it is pending
ID: python/asyncio-task-destroyed-pending
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.
解决方案
-
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)
-
95% 成功率 Use asyncio.gather() directly to manage tasks
results = await asyncio.gather(coro1(), coro2())
无效尝试
常见但无效的做法:
-
Ignoring the warning and letting the task run
70% 失败
The task may be cancelled abruptly, causing incomplete operations and resource leaks.
-
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.