Is the title a valid way to cancel the current Task (in order to trigger a cancellation handler etc.)? What's the worst that can happen?
The main question part of which task (if any) this code would be called. If that is a separate method on a type, which can be called separately from the async code you would like to cancel, and probably not even in async context, then it will either will cancel not the task you may want to cancel, or cancel nothing at all. I would be cautious about using this.
1 Like
Okay thank you. How about inside
Task {
try await withThrowingTaskGroup(of: Void.self) { group in
group.addTask {
return try await withTaskCancellationHandler {
print("Start")
try await Task.cancelCurrent()
} onCancel: {
print("Cancelled!")
}
}
}
}
extension Task where Success == Never, Failure == Never {
static func cancelCurrent() throws {
withUnsafeCurrentTask { task in task?.cancel() }
throw _Concurrency.CancellationError()
}
}
Well, that should work, I suppose. You clearly will have a task to cancel. And throwing an error will prevent the code to continue running. Not sure if that is necessarily the best way (depends on the end goal), but logically that's correct.
1 Like