Why are there 2 variants of withTaskCancellationHandler in Task?

Why are both of these functions a part of Task yet seem to be functionally identical? Which should I use?

One is documented with a discussion and the other is empty. A search of Apple's Async Algorithms shows that the one which starts with handler and operation next is always used. This is the variant which is not documented. It appears they behave the same and have a functionally identical signature for both closures. Should one be deprecated?

The Task API went through significant revisions throughout its development. The withTaskCancellationHandler(operation:onCancel:) version is the final version, and it benefits from multiple trailing closure syntax:

Task.withTaskCancellationHandler {
  // this is your main block of async work
} onCancel: {
  // this is your cancellation handler
1 Like

The first one was recently marked as deprecated - [Concurrency] Deprecate one of the cancellation handler overloads by ktoso · Pull Request #60569 · apple/swift · GitHub

The second one is the final API.


Thanks, this ordering does make it clear which one handles cancellation. The post from Paul Hudson explains this well.

Multiple Trailing Closures (Swift 5.3)

1 Like