Created
April 30, 2024 07:14
-
-
Save Arthraim/0e31ab130fa3c7d211f85a32688c8541 to your computer and use it in GitHub Desktop.
This file contains 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 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