# asyncio 异常：队列获取超时

- **ID:** `python/asyncio-queue-get-timeout`
- **领域:** python
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

带超时的 asyncio.Queue.get() 调用在指定时间内未收到项目。

## 版本兼容性

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

## 解决方案

1. **Use asyncio.wait_for() with a reasonable timeout and handle timeout gracefully** (90% 成功率)
   ```
   try:
    item = await asyncio.wait_for(queue.get(), timeout=5.0)
except asyncio.TimeoutError:
    item = None  # or handle differently
   ```
2. **Use queue.get_nowait() in a loop with sleep** (80% 成功率)
   ```
   while True:
    try:
        item = queue.get_nowait()
        break
    except asyncio.QueueEmpty:
        await asyncio.sleep(0.1)
   ```

## 无效尝试

- **Using a very large timeout to avoid the error** — This may cause the application to hang if items are never produced. (30% 失败率)
- **Polling the queue with qsize() before get()** — qsize() is not reliable in concurrent scenarios due to race conditions. (60% 失败率)
