go runtime_error ai_generated true

context 已取消

context canceled

ID: go/context-canceled-in-goroutine

其他格式: JSON · Markdown 中文 · English
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.

generic

解决方案

  1. 98% 成功率
    select {
    case <-ctx.Done():
        return ctx.Err()
    default:
        // continue
    }
  2. 95% 成功率
    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
    defer cancel()

无效尝试

常见但无效的做法:

  1. 95% 失败

    Ignoring cancellation can lead to resource leaks, wasted work, and violating the contract of context-aware functions.

  2. 90% 失败

    This loses the cancellation signal and any deadlines, potentially causing the goroutine to run indefinitely.