Created
September 18, 2023 09:33
-
-
Save sidepelican/ea9e3e8dffe83baab01a3a712e0cf497 to your computer and use it in GitHub Desktop.
Taskはキャンセルされても明示的にtry Task.checkCancellation()などで抜けない限り最後まで走り抜ける
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 mySleep(seconds: Int) async { | |
await withCheckedContinuation { c in | |
DispatchQueue.global().asyncAfter(deadline: .now() + TimeInterval(seconds)) { | |
c.resume() | |
} | |
} | |
} | |
func throwingFunc() async throws { | |
print(#function, "begin") | |
defer { | |
print(#function, "defer") | |
} | |
await mySleep(seconds: 2) | |
print(#function, "end") | |
} | |
func nonThrowingFunc() async { | |
print(#function, "begin") | |
defer { | |
print(#function, "defer") | |
} | |
await mySleep(seconds: 2) | |
print(#function, "end") | |
} | |
func f1() async throws { | |
await nonThrowingFunc() | |
try await throwingFunc() | |
} | |
func f2() async throws { | |
try await throwingFunc() | |
await nonThrowingFunc() | |
} | |
try Task.checkCancellation() | |
print("----f1----") | |
let t = Task { | |
try await f1() | |
} | |
sleep(1) | |
t.cancel() | |
sleep(5) | |
print("----f2----") | |
let t2 = Task { | |
try await f2() | |
} | |
sleep(1) | |
t2.cancel() | |
sleep(5) | |
print("----end---") |
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
----f1---- | |
nonThrowingFunc() begin | |
nonThrowingFunc() end | |
nonThrowingFunc() defer | |
throwingFunc() begin | |
throwingFunc() end | |
throwingFunc() defer | |
----f2---- | |
throwingFunc() begin | |
throwingFunc() end | |
throwingFunc() defer | |
nonThrowingFunc() begin | |
nonThrowingFunc() end | |
nonThrowingFunc() defer | |
----end--- |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment