Last active
November 9, 2025 09:01
-
-
Save macguru/9b9b42fabcd72c1613b060bb12ee0344 to your computer and use it in GitHub Desktop.
Combines withTaskCancellationHandler with a CheckedContinuation.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import Synchronization | |
| func untilCancelled() async { | |
| print("1") | |
| let mutex: Mutex<CheckedContinuation<Void, Never>?> = .init(nil) | |
| await withTaskCancellationHandler { | |
| print("2") | |
| await withCheckedContinuation { continuation in | |
| print("3") | |
| mutex.withLock { | |
| if Task.isCancelled { | |
| print("abort") | |
| continuation.resume() | |
| return | |
| } | |
| print("4") | |
| $0 = continuation | |
| } | |
| } | |
| } onCancel: { | |
| let continuation = mutex.withLock { | |
| print("5") | |
| return $0.take() | |
| } | |
| continuation?.resume() | |
| } | |
| print("6") | |
| } | |
| func main() async throws { | |
| let hangsForever = Task { | |
| await untilCancelled() | |
| } | |
| // Comment out this line to test early cancellation. | |
| try await Task.sleep(for: .milliseconds(10)) | |
| print("will cancel") | |
| hangsForever.cancel() | |
| print("did cancel") | |
| try await Task.sleep(for: .milliseconds(10)) | |
| } | |
| try await main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Got you, thanks for the explanation