# 运行时错误：事件循环已关闭

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

## 根因

在事件循环已被显式关闭后尝试使用它，通常是因为过早调用 loop.close() 或在关闭后重用循环。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 3.8 | active | — | — |
| 3.9 | active | — | — |
| 3.10 | active | — | — |
| 3.11 | active | — | — |

## 解决方案

1. **Use asyncio.run() for top-level entry point to avoid manual loop management** (95% 成功率)
   ```
   async def main(): await some_coroutine(); asyncio.run(main())
   ```
2. **Check if loop is closed before using it, and create a new one if needed** (85% 成功率)
   ```
   if loop.is_closed(): loop = asyncio.new_event_loop(); asyncio.set_event_loop(loop)
   ```

## 无效尝试

- **Recreating the loop with asyncio.new_event_loop() without setting it as current** — The new loop is not set as the current loop, so asyncio.get_event_loop() still returns a closed loop. (70% 失败率)
- **Ignoring the error and continuing execution** — The closed loop cannot process coroutines, leading to hangs or crashes later. (90% 失败率)
- **Using loop.run_forever() after loop.close()** — A closed loop cannot be restarted; run_forever() raises RuntimeError. (100% 失败率)
