Skip to content

Commit f345f25

Browse files
committed
Cancellation
1 parent 08027b9 commit f345f25

File tree

3 files changed

+37
-1
lines changed

3 files changed

+37
-1
lines changed

Sources/Timeout.swift

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,11 @@ public func withThrowingTimeout<T>(
5656
throw TimeoutError(timeout: seconds)
5757
}
5858

59-
let bodyResult = await bodyTask.result
59+
let bodyResult = await withTaskCancellationHandler {
60+
await bodyTask.result
61+
} onCancel: {
62+
bodyTask.cancel()
63+
}
6064
timeoutTask.cancel()
6165
let timeoutResult = await timeoutTask.result
6266

Tests/TimeoutTests.swift

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,21 @@ struct TimeoutTests {
9090
}
9191
}
9292
}
93+
94+
@Test
95+
func timeout_cancels() async {
96+
let task = Task {
97+
try await withThrowingTimeout(seconds: 1) {
98+
try await Task.sleep(nanoseconds: 1_000_000_000)
99+
}
100+
}
101+
102+
task.cancel()
103+
104+
await #expect(throws: CancellationError.self) {
105+
try await task.value
106+
}
107+
}
93108
}
94109

95110
public struct NonSendable<T> {

Tests/TimeoutXCTests.swift

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,23 @@ final class TimeoutTests: XCTestCase {
9191
XCTAssertTrue(error is TimeoutError)
9292
}
9393
}
94+
95+
func testTimeout_Cancels() async {
96+
let task = Task {
97+
try await withThrowingTimeout(seconds: 1) {
98+
try await Task.sleep(nanoseconds: 1_000_000_000)
99+
}
100+
}
101+
102+
task.cancel()
103+
104+
do {
105+
_ = try await task.value
106+
XCTFail("Expected Error")
107+
} catch {
108+
XCTAssertTrue(error is CancellationError)
109+
}
110+
}
94111
}
95112

96113
public struct NonSendable<T> {

0 commit comments

Comments
 (0)