The following program should run the function longCalculation
twice in parallel if the button is pressed. But the function is called twice in sequence instead.
struct ContentView: View {
@State private var result: Int = 0
var body: some View {
VStack {
Text("Result: \(result)")
Button {
async {
async let result1 = longCalculation()
async let result2 = longCalculation(
self.result = await result1 + result2
print("[end] action / is on main: \(Thread.current.isMainThread)")
}
} label: {
Text("Button")
}
}
}
}
fileprivate func longCalculation() async -> Int {
print("[start] longCalculation / is on main thread: \(Thread.current.isMainThread)")
var c = 0
for _ in 0...10000000 {
c += Int.random(in: 0...100)
c = c % 13
}
print("[end] longCalculation / is on main thread: \(Thread.current.isMainThread)")
return c
}
According to the output the calls are still in sequence. Why does this happen? The two async let
assignments should create two child tasks. Did I miss something?
> [start] longCalculation / is on main thread: false
> [end] longCalculation / is on main thread: false
> [start] longCalculation / is on main thread: false
> [end] longCalculation / is on main thread: false
> [end] action / is on main: true
This is the output when I tested your code on iOS 15 simulator:
[start] longCalculation / is on main thread: false
[start] longCalculation / is on main thread: false
[end] longCalculation / is on main thread: false
[end] longCalculation / is on main thread: false
[end] action / is on main: true
Can you clarify your environment used for the test?