在GoLang中取消上下文时如何在函数中立即返回?

package main


import (

    "context"

    "fmt"

    "time"

)


func main() {

    ctx := context.Background()

    c, fn := context.WithCancel(ctx)

    go doSth(c)

    time.Sleep(1 * time.Second)

    fn()

    time.Sleep(10 * time.Second)

}


func doSth(ctx context.Context) {

    fmt.Println("doing")

    time.Sleep(2 * time.Second)

    fmt.Println("still doing")

    select {

    case <-ctx.Done():

        fmt.Println("cancel")

        return

    }

}

输出:


doing

still doing

cancel

我不知道当它获得的上下文是取消时如何使这个 doSth 函数返回。


换句话说,我希望这个函数的输出是:


输出:


doing

cancel


宝慕林4294392
浏览 121回答 1
1回答

梦里花落0921

您可以使用计时器,它将在给定的持续时间后通过通道发送消息。这允许您将其添加到选择中。func main() {&nbsp; &nbsp; ctx := context.Background()&nbsp; &nbsp; c, fn := context.WithCancel(ctx)&nbsp; &nbsp; go doSth(c)&nbsp; &nbsp; time.Sleep(1 * time.Second)&nbsp; &nbsp; fn()&nbsp; &nbsp; time.Sleep(10 * time.Second)}func doSth(ctx context.Context) {&nbsp; &nbsp; fmt.Println("doing")&nbsp; &nbsp; timer := time.NewTimer(2 * time.Second)&nbsp; &nbsp; select {&nbsp; &nbsp; case <-timer.C:&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("still doing")&nbsp; &nbsp; case <-ctx.Done():&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("cancel")&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go