2 回答

TA貢獻1875條經(jīng)驗 獲得超3個贊
使用context.Context指示 go 例程中止其功能。當(dāng)然,Go 例程必須偵聽此類取消事件。
因此,對于您的代碼,請執(zhí)行以下操作:
ctx := req.Context() // this will be implicitly canceled by your TimeoutHandler after 1s
i := 0
for {
? ? if i == 500 {
? ? ? ? break
? ? }
? ? // for any long wait (1s etc.) always check the state of your context
? ? select {
? ? case <-time.After(1 * time.Second): // no cancelation, so keep going
? ? case <-ctx.Done():
? ? ? ? fmt.Println("request context has been canceled:", ctx.Err())
? ? ? ? return // terminates go-routine
? ? }
? ? i++
}
注意:?Context
被設(shè)計為鏈?zhǔn)降?- 允許以級聯(lián)方式取消多個級別的子任務(wù)。
在典型的 REST 調(diào)用中,我們會發(fā)起數(shù)據(jù)庫請求。因此,為了確保此類阻塞和/或緩慢的調(diào)用及時完成,不應(yīng)使用Query?,而應(yīng)使用QueryContext?- 將 http 請求的上下文作為第一個參數(shù)傳遞。

TA貢獻1794條經(jīng)驗 獲得超8個贊
我發(fā)現(xiàn),如果你沒有任何方法到達你的頻道,那么當(dāng) goroutine 運行時就沒有辦法殺死或停止它。
在大型計算任務(wù)中,您必須在特定時間間隔或特定任務(wù)完成后觀看通道。
- 2 回答
- 0 關(guān)注
- 186 瀏覽
添加回答
舉報