Skip to content

Instantly share code, notes, and snippets.

@sidepelican
Created September 18, 2023 09:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sidepelican/ea9e3e8dffe83baab01a3a712e0cf497 to your computer and use it in GitHub Desktop.
Save sidepelican/ea9e3e8dffe83baab01a3a712e0cf497 to your computer and use it in GitHub Desktop.
Taskはキャンセルされても明示的にtry Task.checkCancellation()などで抜けない限り最後まで走り抜ける
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---")
----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