It’s weird that you’re seeing different behaviour here. On my Mac (running 12.6) neither prints in task in main
, and that’s what I’d expect. You’ve started an unstructured task and told it to run independently of the task running main()
. At some point that task will run but, before that happens, you return from main()
, which terminates your entire process.
Consider this program:
@main
struct Dummy {
static func main() async {
_ = Task { print("in task in main") }
print("in main 1")
print("in main 2")
print("in main 3")
print("in main 4")
print("in main 5")
try! await Task.sleep(nanoseconds: 1_000)
print("in main 6")
}
}
It prints
in main 1
in main 2
in main 3
in main 4
in main 5
in task in main
in main 6
because the sleep gives the program enough time to spin up the task.
The best way to avoid this problem is to use structured concurrency. That guarantees that every task started in a scope has completed before that scope does away. So, something like this:
func task() async -> Int {
print("in task in main")
return 42
}
@main
struct Dummy {
static func main() async {
async let result = task()
print("in main 1")
print("in main 2")
print("in main 3")
print("in main 4")
print("in main 5")
try! await Task.sleep(nanoseconds: 1_000)
print("in main 6")
print(await result)
}
}
Alternatively, you can continue using unstructured concurrency and explicitly wait for your task:
@main
struct Dummy {
static func main() async {
let t = Task { print("in task in main") }
print("in main 1")
print("in main 2")
print("in main 3")
print("in main 4")
print("in main 5")
print(await t.result)
print("in main 6")
}
}
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"