Skip to content

Instantly share code, notes, and snippets.

@Arthraim
Created April 30, 2024 07:14
Show Gist options
  • Save Arthraim/0e31ab130fa3c7d211f85a32688c8541 to your computer and use it in GitHub Desktop.
Save Arthraim/0e31ab130fa3c7d211f85a32688c8541 to your computer and use it in GitHub Desktop.
import Foundation
func longRunningTask() async throws {
// Simulate a long-running task
print("Long-running task started")
try await Task.sleep(nanoseconds: UInt64(60 * Double(NSEC_PER_SEC)))
print("Long-running task completed")
}
func timerTask() async throws {
print("Timer task started")
// Set a 30-second timer
try await Task.sleep(nanoseconds: UInt64(10 * Double(NSEC_PER_SEC)))
print("Timer reached end")
}
struct TimeoutError: Error {}
func testCancellation() async {
do {
try await withThrowingTaskGroup(of: Void.self) { group -> Void in
group.addTask {
try await longRunningTask()
print("Long-running task is cancelled: \(Task.isCancelled)")
}
group.addTask {
try await timerTask()
throw TimeoutError()
}
try await group.next()
}
} catch {
print("Error thrown: \(error.localizedDescription)")
}
}
await testCancellation()
print("here")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment