# RuntimeError: 事件循环已关闭

- **ID:** `python/event-loop-closed-runtimeerror`
- **领域:** python
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

在创建它的 asyncio 事件循环已关闭后，仍复用了协程或 aiohttp 会话。常见于多次调用 asyncio.run()，或在循环外创建 ClientSession 却在另一次 asyncio.run() 内使用。底层 transport/socket 绑定在已失效的循环上。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 3.8+ | active | — | — |
| 3.10+ | active | — | — |
| 3.12 | active | — | — |

## 解决方案

1. **** (95% 成功率)
   ```
   async def main():
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as r:
            return await r.text()

asyncio.run(main())  # session lives and dies inside this loop
   ```
2. **** (85% 成功率)
   ```
   import asyncio
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
    loop.run_until_complete(main())
finally:
    loop.run_until_complete(loop.shutdown_asyncgens())
    loop.close()
   ```

## 无效尝试

- **** — Silencing the exception leaves the coroutine unfinished and leaks resources; the next call fails differently or hangs. (90% 失败率)
- **** — A closed loop cannot be restarted; run_until_complete raises RuntimeError immediately. (95% 失败率)
- **** — Policy changes do not resurrect a closed loop; the error is lifecycle, not platform. (85% 失败率)
