python runtime_error ai_generated true

asyncio.exceptions.InvalidStateError: 任务尚未完成

asyncio.exceptions.InvalidStateError: Task is not done

ID: python/asyncio-queue-task-done-never-set

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

版本兼容性

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

根因分析

在任务完成之前调用了 task.result() 或 task.exception(),二者都要求任务处于 DONE 状态。

English

task.result() or task.exception() was called before the task completed; both require the task to be in the DONE state.

generic

解决方案

  1. 97% 成功率
    task = asyncio.create_task(work())
    result = await task
  2. 92% 成功率
    done, pending = await asyncio.wait({task}, timeout=10)
    if task in done:
        print(task.result())

无效尝试

常见但无效的做法:

  1. 80% 失败

    Arbitrary sleeps are racy; under load the task may still be pending.

  2. 70% 失败

    Busy-looping until done wastes CPU and does not guarantee completion.