Two `async let` do not run the calculation in parallel

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
Answered by OOPer in 678741022

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?

Accepted Answer

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?

By the way, if I put longCalculation on a concurrent GCD queue than it works as expected. But I wonder if it is really meant to be like this.

I got this link from a Reddit user: https://twitter.com/rokhinip/status/1403375411732439044

So, now it is clear that the code should work as expected but it doesn't because I am still on Big Sur.

Two `async let` do not run the calculation in parallel
 
 
Q