swiftasynchronousasync-awaitgrand-central-dispatchswift5

How to call async function asynchronously without awaiting for the result


Let's say I have the following functions.

func first() async {
    print("first")
}

func second() {
   print("second")
}

func main() {
   Task {
      await first()
   }
   second()
}

main()

Even though marking first function as async does not make any sense as there is no async work it does, but still it is possible...

I was expecting that even though the first function is being awaited, it will be called asynchronously.

But actually the output is

first 
second

How would I call the fist function asynchronously mimicking the GCD's variant of:

DispatchQueue.current.async { first() }
second()

Solution

  • This behavior will change depending upon the context.

    So, the question is, do you really care which order these two tasks start? If so, you can eliminate the race by (obviously) putting the Task { await first() } after the call to second. Or do you simply want to ensure that second won’t wait for first to finish? In that case, this already is the behavior and no change to your code is required.


    You asked:

    What if await first() needs to be run on the same queue as second() but asynchronously. … I am just thinking [that if it runs on background thread that it] would mean crashes due to updates of UI not from the main thread.

    You can mark the routine to update the UI with @MainActor, which will cause it to run on the main thread. But note, do not use this qualifier with the time-consuming task, itself (because you do not want to block the main thread), but rather decouple the time-consuming operation from the UI update, and just mark the latter as @MainActor.

    E.g., here is an example that manually calculates π asynchronously, and updates the UI when it is done:

    func startCalculation() {
        Task {
            let pi = await calculatePi()
            updateWithResults(pi)
        }
        updateThatCalculationIsUnderway() // this really should go before the Task to eliminate any races, but just to illustrate that this second routine really does not wait
    }
    
    // deliberately inefficient calculation of pi
    
    func calculatePi() async -> Double {
        await Task.detached {
            var value: Double = 0
            var denominator: Double = 1
            var sign: Double = 1
            var increment: Double = 0
    
            repeat {
                increment = 4 / denominator
                value += sign * 4 / denominator
                denominator += 2
                sign *= -1
            } while increment > 0.000000001
    
            return value
        }.value
    }
    
    func updateThatCalculationIsUnderway() {
        statusLabel.text = "Calculating π"
    }
    
    @MainActor
    func updateWithResults(_ value: Double) {
        statusLabel.text = "Done"
        resultLabel.text = formatter.string(for: value)
    }
    

    Note: To ensure this slow synchronous calculation of calculatePi is not run on the current actor (presumably the main actor), we want an “unstructured task”. Specifically, we want a “detached task”, i.e., one that is not run on the current actor. As the Unstructured Concurrency section of The Swift Programming Language: Concurrency: Tasks and Task Groups says:

    To create an unstructured task that runs on the current actor, call the Task.init(priority:operation:) initializer. To create an unstructured task that’s not part of the current actor, known more specifically as a detached task, call the Task.detached(priority:operation:) class method.