python runtime_error ai_generated true

asyncio.exceptions.InvalidStateError: Task is not done

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

Also available as: JSON · Markdown · 中文
80%Fix Rate
87%Confidence
0Evidence
2024-07-04First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.8+ active
3.9+ active
3.10+ active
3.11+ active
3.12+ active

Root Cause

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

generic

中文

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

Workarounds

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

Dead Ends

Common approaches that don't work:

  1. 80% fail

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

  2. 70% fail

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