# 恐慌：运行时错误：向已关闭的通道发送数据（上下文取消）

- **ID:** `go/context-cancellation-ignore`
- **领域:** go
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

当上下文被取消时，其通道被关闭；向其发送数据会导致恐慌。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 1.7 | active | — | — |
| 1.23 | active | — | — |

## 解决方案

1. **Use select with context.Done() to avoid sending on closed channel** (95% 成功率)
   ```
   select {
case ch <- data:
case <-ctx.Done():
    return ctx.Err()
}
   ```
2. **Create a new channel for each operation and close it safely** (90% 成功率)
   ```
   ch := make(chan int, 1)
select {
case ch <- data:
case <-ctx.Done():
    close(ch)
    return ctx.Err()
}
   ```

## 无效尝试

- **Checking context.Err() before send but not handling race condition** — Context can be cancelled between check and send. (70% 失败率)
- **Using a separate channel that is not closed on cancellation** — Ignores the cancellation signal, leading to resource leaks. (60% 失败率)
