3 回答

TA貢獻(xiàn)1850條經(jīng)驗(yàn) 獲得超11個(gè)贊
由于 context.Context 是一個(gè)接口,您可以簡(jiǎn)單地創(chuàng)建自己的永遠(yuǎn)不會(huì)取消的實(shí)現(xiàn):
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貢獻(xiàn)1868條經(jīng)驗(yàn) 獲得超4個(gè)贊
誰(shuí)能建議應(yīng)該如何完成?
是的。不要這樣做。
如果您需要不同的上下文,例如對(duì)于您的異步后臺(tái)任務(wù),則創(chuàng)建一個(gè)新的上下文。您的傳入上下文和您的后臺(tái)任務(wù)之一無(wú)關(guān),因此您不能嘗試重用傳入的上下文。
如果不相關(guān)的新上下文需要來(lái)自原始上下文的一些數(shù)據(jù):復(fù)制您需要的內(nèi)容并添加新內(nèi)容。

TA貢獻(xiàn)1772條經(jīng)驗(yàn) 獲得超5個(gè)贊
從 go 1.21 開始,此功能將通過(guò)以下方式直接在標(biāo)準(zhǔn)庫(kù)中提供context.WithoutCancel
:
func?WithoutCancel(parent?Context)?Context
WithoutCancel
返回 parent 的副本,當(dāng) parent 被取消時(shí),該副本未被取消。返回的上下文不返回Deadline
or?Err
,其Done
通道為nil
。調(diào)用Cause
返回的上下文返回nil
。
- 3 回答
- 0 關(guān)注
- 153 瀏覽
添加回答
舉報(bào)