亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

上下文 - WithDeadline() 與 WithTimeout()

上下文 - WithDeadline() 與 WithTimeout()

Go
MMMHUHU 2022-07-11 10:36:56
下面的代碼:// Sample program to show how to use the WithDeadline function// of the Context package.package mainimport (    "context"    "fmt"    "time")type data struct {    UserID string}func main() {    // Set a duration.    // duration := 150 * time.Millisecond    duration := time.Now().Add(3 * time.Second)    // Create a context that is both manually cancellable and will signal    // a cancel at the specified duration.    ctx, cancel := context.WithDeadline(context.Background(), duration)    defer cancel()    // Create a channel to received a signal that work is done.    ch := make(chan data, 1)    // Ask the goroutine to do some work for us.    go func() {        // Simulate work.        time.Sleep(50 * time.Millisecond)        // Report the work is done.        ch <- data{"123"}    }()    // Wait for the work to finish. If it takes too long move on.    select {    case d := <-ch:        fmt.Println("work complete", d)    case <-ctx.Done():        fmt.Println("work cancelled")    }}用于WithDeadline發送 timer'd cancel()。這可以使用以下方法完成:duration := 150 * time.Millisecond// Create a context that is both manually cancellable and will signal// a cancel at the specified duration.ctx, cancel := context.WithTimeout(context.Background(), duration)在內部,context.WithTimeout調用該context.WithDeadline函數并通過將超時添加到當前時間來生成截止日期。有多么context.WithTimeout()不同context.WithDeadline()
查看完整描述

2 回答

?
慕桂英4014372

TA貢獻1871條經驗 獲得超13個贊

context.WithTimeout() 與 context.WithDeadline() 有何不同

第一個需要一段持續時間,然后從現在開始取消,第二個是調用取消的絕對時間,如文檔中所述,值得像往常一樣閱讀。


查看完整回答
反對 回復 2022-07-11
?
函數式編程

TA貢獻1807條經驗 獲得超9個贊

WithTimeout是執行的便捷函數WithDeadline(parent, time.Now().Add(timeout))。

這些功能在應用程序如何指定截止日期方面有所不同。否則它們是相同的。

調用適合您手頭值的函數。


查看完整回答
反對 回復 2022-07-11
  • 2 回答
  • 0 關注
  • 412 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號