# asyncio.exceptions.CancelledError：任务被销毁但仍在等待中！

- **ID:** `python/asyncio-gather-cancelled-error`
- **领域:** python
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

使用 asyncio.gather() 且 return_exceptions=False 时，如果某个任务因超时等原因抛出 CancelledError，gather 被取消，其他任务未被正确等待，导致待处理任务销毁警告。

## 版本兼容性

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

## 解决方案

1. **** (90% 成功率)
   ```
   results = await asyncio.gather(*tasks, return_exceptions=True)
for r in results:
    if isinstance(r, asyncio.CancelledError):
        # handle cancellation gracefully
   ```
2. **** (85% 成功率)
   ```
   done, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_EXCEPTION)
for task in pending:
    task.cancel()
await asyncio.gather(*pending, return_exceptions=True)
   ```

## 无效尝试

- **** — CancelledError is not always raised synchronously; it can be raised during await, and ignoring it may leave tasks in inconsistent states. (60% 失败率)
- **** — Shield only protects against cancellation of the outer task, not the inner tasks; it doesn't solve the root issue of pending tasks. (70% 失败率)
