python runtime_error ai_generated true

asyncio.exceptions.CancelledError:

ID: python/asyncio-cancellederror

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

版本兼容性

版本状态引入弃用备注
3.8 active — — —
3.9 active — — —
3.10 active — — —
3.11 active — — —
3.12 active — — —

根因分析

任务被取消(例如由 asyncio.wait_for 超时或外部取消触发),CancelledError 在用户代码中传播,未在清理后重新抛出。

English

A task was cancelled (e.g. by asyncio.wait_for timeout or an outer cancellation), and the CancelledError propagated up through user code without being re-raised after cleanup.

generic

解决方案

  1. 95% 成功率
    Run cleanup then re-raise:
    
    try:
        await work()
    except asyncio.CancelledError:
        await cleanup()
        raise
  2. 90% 成功率
    Use contextlib.suppress(asyncio.CancelledError) only around cleanup awaits, never around the main work.
  3. 85% 成功率
    Use asyncio.shield() around critical sections that must not be cancelled.

无效尝试

常见但无效的做法:

  1. 90% 失败

    In 3.8+ CancelledError inherits from BaseException, so this doesn't catch it anyway; and catching it silently breaks cancellation semantics.

  2. 85% 失败

    Swallows cancellation, leaving parent tasks hanging and breaking structured concurrency.

  3. 80% 失败

    Re-cancelling without re-raising still doesn't propagate cancellation up the stack.