go
runtime_error
ai_generated
true
context 已取消
context canceled
ID: go/context-canceled-in-goroutine
80%修复率
88%置信度
0证据数
2024-10-12首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 1.7+ | active | — | — | — |
根因分析
上下文被取消(由于超时、截止时间或显式取消),而某个 goroutine 仍在使用它。该 goroutine 从遵循上下文的函数中收到 context.Canceled 错误。
English
A context was canceled (either by timeout, deadline, or explicit cancel) while a goroutine was still using it. The goroutine receives context.Canceled error from a function that respects the context.
解决方案
-
98% 成功率
select { case <-ctx.Done(): return ctx.Err() default: // continue } -
95% 成功率
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel()
无效尝试
常见但无效的做法:
-
95% 失败
Ignoring cancellation can lead to resource leaks, wasted work, and violating the contract of context-aware functions.
-
90% 失败
This loses the cancellation signal and any deadlines, potentially causing the goroutine to run indefinitely.