# asyncio 异常：任务被销毁但仍在挂起状态

- **ID:** `python/asyncio-task-destroyed-pending`
- **领域:** python
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

任务在仍处于挂起状态时被垃圾回收，通常是因为丢失了对任务的引用。

## 版本兼容性

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

## 解决方案

1. **Store the task in a list or variable to keep a reference** (90% 成功率)
   ```
   tasks = []
task = asyncio.create_task(coro())
tasks.append(task)
await asyncio.gather(*tasks)
   ```
2. **Use asyncio.gather() directly to manage tasks** (95% 成功率)
   ```
   results = await asyncio.gather(coro1(), coro2())
   ```

## 无效尝试

- **Ignoring the warning and letting the task run** — The task may be cancelled abruptly, causing incomplete operations and resource leaks. (70% 失败率)
- **Using asyncio.ensure_future() without storing the task** — ensure_future() returns a task, but if not stored, it may be garbage collected while pending. (60% 失败率)
