Skip to content

Commit

Permalink
Cancellation
Browse files Browse the repository at this point in the history
  • Loading branch information
swhitty committed Sep 8, 2024
1 parent 08027b9 commit 0799953
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 1 deletion.
6 changes: 5 additions & 1 deletion Sources/Timeout.swift
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,11 @@ public func withThrowingTimeout<T>(
throw TimeoutError(timeout: seconds)
}

let bodyResult = await bodyTask.result
let bodyResult = await withTaskCancellationHandler {
await bodyTask.result
} onCancel: {
bodyTask.cancel()
}
timeoutTask.cancel()
let timeoutResult = await timeoutTask.result

Expand Down
15 changes: 15 additions & 0 deletions Tests/TimeoutTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,21 @@ struct TimeoutTests {
}
}
}

@Test
func timeout_cancels() async {
let task = Task {
try await withThrowingTimeout(seconds: 1) {
try await Task.sleep(nanoseconds: 1_000_000_000)
}
}

task.cancel()

await #expect(throws: CancellationError.self) {
try await task.value
}
}
}

public struct NonSendable<T> {
Expand Down
17 changes: 17 additions & 0 deletions Tests/TimeoutXCTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,23 @@ final class TimeoutTests: XCTestCase {
XCTAssertTrue(error is TimeoutError)
}
}

func timeout_cancels() async {
let task = Task {
try await withThrowingTimeout(seconds: 1) {
try await Task.sleep(nanoseconds: 1_000_000_000)
}
}

task.cancel()

do {
_ = try await task.value
XCTFail("Expected Error")
} catch {
XCTAssertTrue(error is CancellationError)
}
}
}

public struct NonSendable<T> {
Expand Down

0 comments on commit 0799953

Please sign in to comment.