Question about the return value of Task.withTaskCancellationHandler

I'm reading the concurrency chapter of the official documentation The Swift Programming Language, Here, in the Task Cancellation part, there's a code like the:

let task = await Task.withTaskCancellationHandler {
    // ...
} onCancel: {
    print("Canceled!")
}


// ... some time later...
task.cancel()  // Prints "Canceled!"

Is this code correct? I mean, isn't Task.withTaskCancellationHandler suppose to return the return value of the operation closure, instead of the Task instance? So in this case, the task variable should be the return value of the closure, and calling task.cancel() should not be valid. Is it actually the documentation wrong or am I not understanding it well? Hope someone can answer this, it can help me as a starter a lot and I would strongly appreciate it!

I agree this example is sort of confusing, and it's also using a deprecated API which isn't ideal. Probably the code structure should be more like this:

let task = Task {
  await withTaskCancellationHandler {
    // ...
  } onCancel: {
    print("Canceled!")
  }
}

// ... some time later...
task.cancel()  // Prints "Canceled!"

I'd recommend filing a bug report against the book repo if you have the time/motivation: Issues · swiftlang/swift-book · GitHub.

3 Likes

Thanks!

1 Like