When should you mark a function `async`?

It makes sense: await / async will hop to a background thread, so if it so happens that the read / readir wrapper is called on the main thread - main thread will not be blocked:

func readAsync() async {
    dispatchPrecondition(condition: .notOnQueue(.main))
    read(...)
}

@MainActor
func testProc() async {
    print("testProc started")
    dispatchPrecondition(condition: .onQueue(.main))
    await readAsync()
    dispatchPrecondition(condition: .onQueue(.main))
    print("testProc ended")
}

Task {
    dispatchPrecondition(condition: .notOnQueue(.main))
    await testProc()
}
RunLoop.main.run(until: .distantFuture)
print()

BTW, consider using existing async analogue of read (e.g. fileURL.resourceBytes).

2 Likes