python runtime_error ai_generated true

asyncio.exceptions.CancelledError:任务被取消

asyncio.exceptions.CancelledError: Task was cancelled

ID: python/asyncio-task-cancellation-not-handled

其他格式: JSON · Markdown 中文 · English
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.

generic

解决方案

  1. 95% 成功率
    try:
        await long_operation()
    except asyncio.CancelledError:
        # cleanup resources
        raise  # re-raise to acknowledge cancellation
  2. 80% 成功率
    result = await asyncio.shield(critical_operation())

无效尝试

常见但无效的做法:

  1. 70% 失败

    Ignoring cancellation can violate asyncio's cooperative cancellation model and lead to tasks that never truly cancel.

  2. 40% 失败

    Finally runs but the exception propagates; if not caught, it may still terminate the task.