有没有办法保护业务逻辑的执行免受上下文取消?这是代码片段,可以更好地理解我的问题
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 循环中开始时,它不应该停止,直到它完成该迭代。这可以使用上下文取消吗?或者我应该使用其他方法,请建议。