3 回答

TA貢獻1850條經驗 獲得超11個贊
由于 context.Context 是一個接口,您可以簡單地創建自己的永遠不會取消的實現:
import (
"context"
"time"
)
type noCancel struct {
ctx context.Context
}
func (c noCancel) Deadline() (time.Time, bool) { return time.Time{}, false }
func (c noCancel) Done() <-chan struct{} { return nil }
func (c noCancel) Err() error { return nil }
func (c noCancel) Value(key interface{}) interface{} { return c.ctx.Value(key) }
// WithoutCancel returns a context that is never canceled.
func WithoutCancel(ctx context.Context) context.Context {
return noCancel{ctx: ctx}
}

TA貢獻1868條經驗 獲得超4個贊
誰能建議應該如何完成?
是的。不要這樣做。
如果您需要不同的上下文,例如對于您的異步后臺任務,則創建一個新的上下文。您的傳入上下文和您的后臺任務之一無關,因此您不能嘗試重用傳入的上下文。
如果不相關的新上下文需要來自原始上下文的一些數據:復制您需要的內容并添加新內容。

TA貢獻1772條經驗 獲得超5個贊
從 go 1.21 開始,此功能將通過以下方式直接在標準庫中提供context.WithoutCancel
:
func?WithoutCancel(parent?Context)?Context
WithoutCancel
返回 parent 的副本,當 parent 被取消時,該副本未被取消。返回的上下文不返回Deadline
or?Err
,其Done
通道為nil
。調用Cause
返回的上下文返回nil
。
- 3 回答
- 0 關注
- 154 瀏覽
添加回答
舉報