python
runtime_error
ai_generated
true
asyncio.exceptions.CancelledError:任务被取消
asyncio.exceptions.CancelledError: Task was cancelled
ID: python/asyncio-task-cancellation-not-handled
80%修复率
87%置信度
0证据数
2024-03-22首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.8 | active | — | — | — |
| 3.9 | active | — | — | — |
| 3.10 | active | — | — | — |
根因分析
协程在等待操作时被取消,但未处理 CancelledError,导致任务突然终止并可能使资源未清理。
English
A coroutine that is cancelled while awaiting an operation does not handle CancelledError, causing the task to terminate abruptly and potentially leaving resources unclean.
解决方案
-
95% 成功率
try: await long_operation() except asyncio.CancelledError: # cleanup resources raise # re-raise to acknowledge cancellation -
80% 成功率
result = await asyncio.shield(critical_operation())
无效尝试
常见但无效的做法:
-
70% 失败
Ignoring cancellation can violate asyncio's cooperative cancellation model and lead to tasks that never truly cancel.
-
40% 失败
Finally runs but the exception propagates; if not caught, it may still terminate the task.