有没有办法保护业务逻辑的执行免受上下文取消的影响?这是代码片段,以便更好地理解我的问题
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 循环中开始时,在完成该迭代之前不应停止。使用上下文取消是否可以这样做?或者我应该使用另一种方法,请建议。
缥缈止盈
相关分类