After changing our main method to become async, with a logic that looks like the following:
static func main() async throws {
// A special startup case that does something in the background and kills the app
if someCondition {
try await someAsyncCode()
exit(0)
}
_ = NSApplicationMain(CommandLine.argc, CommandLine.unsafeArgv)
}
we started seeing several crashes that start like this:
... etc
30 AppKit _DPSNextEvent
31 AppKit -[NSApplication(NSEvent) _nextEventMatchingEventMask:untilDate:inMode:dequeue:]
32 AppKit -[NSApplication run]
33 AppKit NSApplicationMain
34 MyApp (1) suspend resume partial function for static AppMain.main() (<compiler-generated>:0)
35 MyApp
[crash.txt](https://developer.apple.com/forums/content/attachment/33f37f09-32be-465b-a2e2-7312fab10597)
(1) await resume partial function for specialized thunk for @escaping @convention(thin) @async () -> () (<compiler-generated>:0)
36 libswift_Concurrency.dylib completeTaskAndRelease(swift::AsyncContext*, swift::SwiftError*)
I realize there's not a lot of detail and I'm willing to expand on the code and the errors if needed, but I'm wondering if anyone has seen this type of issue after making their main method async.
After changing our main method to become async
Gosh, that seems like a bad idea. NSApplicationMain was not designed to be called from an async function. Try something like this instead:
import Cocoa
func main() {
if UserDefaults.standard.bool(forKey: "RunInSpecialMode") {
Task {
for _ in 0..<3 {
print("sleep")
fflush(stdout)
try? await Task.sleep(for: .seconds(1))
}
print("done")
fflush(stdout)
exit(0)
}
dispatchMain()
}
_ = NSApplicationMain(CommandLine.argc, CommandLine.unsafeArgv)
}
main()
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"