python runtime_error ai_generated true

RuntimeError: 任务 <Task pending name='Task-1' coro=<foo()>> 获得了附加到不同事件循环的 Future <Future pending>

RuntimeError: Task <Task pending name='Task-1' coro=<foo()>> got Future <Future pending> attached to a different loop

ID: python/asyncio-task-got-future-different-loop

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

版本兼容性

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

根因分析

在一个事件循环下创建的协程在另一个循环中被 await,导致其持有的 Future 与等待它的 Task 属于不同的事件循环。

English

A coroutine created under one event loop is awaited under another loop, so the Future it holds belongs to a different loop than the Task waiting on it.

generic

解决方案

  1. 90% 成功率
    async def main():
        # session created inside the loop that will use it
        async with aiohttp.ClientSession() as session:
            await session.get(url)
    
    asyncio.run(main())
  2. 85% 成功率
    future = asyncio.run_coroutine_threadsafe(coro(), target_loop)
    result = future.result(timeout=10)

无效尝试

常见但无效的做法:

  1. 75% 失败

    get_event_loop() can return the same stale loop or raise DeprecationWarning in newer versions; it does not reconcile two loops.

  2. 90% 失败

    Sleeping does not migrate a Future between loops; the ownership mismatch remains.