防止上下文取消在业务逻辑中停止函数执行

有没有办法保护业务逻辑的执行免受上下文取消的影响?这是代码片段,以便更好地理解我的问题


func main() {

    ctx, cancel := context.WithCancel(context.Background())

    go foo(ctx)

    time.Sleep(time.Second * 3)

    cancel()

}


func foo(ctx context.Context) {

    // batch process data

    // context cancel should not stop function execution 

    // in the middle of business logic

    for i:= 0; i<10; i++ {

        fmt.Println("START of business logic for ID:", i)

        fmt.Println("Critical component")

        fmt.Print("Saving changes to DB...")

        time.Sleep(time.Second * 1)

        fmt.Println("Done")

        fmt.Println("END of business logic for ID:", i)

    }

}

输出:


START of business logic for ID: 0

Critical component

Saving changes to DB...Done

END of business logic for ID: 0

START of business logic for ID: 1

Critical component

Saving changes to DB...Done

END of business logic for ID: 1

START of business logic for ID: 2

Critical component

Saving changes to DB...Done

END of business logic for ID: 2

当执行在 for 循环中开始时,在完成该迭代之前不应停止。使用上下文取消是否可以这样做?或者我应该使用另一种方法,请建议。


去游乐场链接


守着一只汪
浏览 75回答 1
1回答

缥缈止盈

上下文取消是任务的信号机制。它不能确保执行 - 这留给任务。这允许任务在中止较大操作之前完成关键子任务。因此,在您的理论示例中,任何关键子步骤都应忽略取消 - 并且只有在它们完成后才轮询上下文:select {&nbsp; &nbsp; case <-ctx.Done():&nbsp; &nbsp; &nbsp; &nbsp; return ctx.Err() // we're cancelled, abort&nbsp; &nbsp; default:}编辑:应用于您的示例for i := 0; i < 10; i++ {&nbsp; &nbsp; //&nbsp; &nbsp; // critical section&nbsp; &nbsp; //&nbsp; &nbsp; // ...&nbsp; &nbsp; select {&nbsp; &nbsp; case <-ctx.Done():&nbsp; &nbsp; &nbsp; &nbsp; return ctx.Err() // we're cancelled, abort&nbsp; &nbsp; default:&nbsp; &nbsp; }}https://play.golang.org/p/kZ39VEVyP4L
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go