python
runtime_error
ai_generated
true
asyncio 异常:任务中引发了 CancelledError
asyncio.exceptions.CancelledError: CancelledError raised in task
ID: python/asyncio-task-cancellation-error
80%修复率
86%置信度
0证据数
2025-06-15首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.8 | active | — | — | — |
| 3.9 | active | — | — | — |
根因分析
任务被外部取消(例如通过 task.cancel()),且未处理取消操作,导致其传播。
English
A task was cancelled externally (e.g., via task.cancel()), and the cancellation was not handled, causing it to propagate.
解决方案
-
90% 成功率 Catch CancelledError and perform cleanup, then re-raise
try: await long_running_coro() except asyncio.CancelledError: # cleanup resources raise -
85% 成功率 Use asyncio.shield() to protect critical sections
await asyncio.shield(critical_coro())
无效尝试
常见但无效的做法:
-
Catching all exceptions except CancelledError
70% 失败
CancelledError is a subclass of BaseException, so it may not be caught by except Exception.
-
Ignoring cancellation and continuing execution
50% 失败
The event loop may be shutting down, and ignoring cancellation can cause resource leaks or hangs.