# 后台任务异常: RuntimeError: 事件循环已关闭

- **ID:** `python/starlette-background-task-exception`
- **领域:** python
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

BackgroundTask 在响应发送后、事件循环拆除后尝试使用事件循环，常见于测试或使用 loop.run_until_complete 时。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 3.x | active | — | — |

## 解决方案

1. **** (90% 成功率)
   ```
   Use httpx.AsyncClient with ASGITransport in tests to keep loop alive
   ```
2. **** (82% 成功率)
   ```
   Prefer sync def background tasks for I/O that must complete after response
   ```

## 无效尝试

- **** — Loop is already closed; cannot recover. (80% 失败率)
- **** — Same closed-loop issue in test environments. (70% 失败率)
