Skip to content

Instantly share code, notes, and snippets.

@sidepelican
Created September 18, 2023 09:08
Show Gist options
  • Save sidepelican/6322569af424cf5d18c0babc457a8095 to your computer and use it in GitHub Desktop.
Save sidepelican/6322569af424cf5d18c0babc457a8095 to your computer and use it in GitHub Desktop.
TaskLocalの引き継ぎはasync letやTask {}では行われる
import Foundation
enum MyValue {
@TaskLocal static var foo: Int = 0
}
func myFunc(@_inheritActorContext _ op: @Sendable @escaping () async -> ()) async {
await withCheckedContinuation { c in
DispatchQueue.global().async {
Task {
await op()
c.resume(returning: ())
}
}
}
}
func myFunc2(_ op: @Sendable @escaping () async -> ()) async {
Task {
await op()
}
}
let task = Task {
print(#line, MyValue.foo)
await MyValue.$foo.withValue(1) {
print(#line, MyValue.foo)
await myFunc {
print(#line, MyValue.foo)
}
async let aa = myFunc2 {
print(#line, MyValue.foo)
}
await myFunc2 {
print(#line, MyValue.foo)
}
await aa
}
}
task.cancel()
print("main end")
25 0
27 1
main end
29 0
35 1
32 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment