Thursday, October 14, 2021

XPC Service’s Methods Not Necessarily Run on Main Thread

Matthias Gansrigler:

After subsequently moving them into an XPC service and thinking it would “just work”, I found that it didn’t. At least not reliably. Maybe every 8th or 9th time, yes, it did all it was asked to do, but every other time, it outright refused to execute Apple Scripts.

After two days of desperate attempts to get it working correctly, and almost giving up on the XPC privilege separation entirely for this, I figured I’d check to see if the Apple Scripts were being executed on the main thread.

Update (2021-10-15): Thomas Clement:

It is documented that NSXPCConnection calls back on the connection’s internal private queue.

Todd Ditchendorf:

I was tinkering with creating an app with an XPC service around 2013 and gave up cos it was flakey. In hindsight, I’m pretty sure this was the problem.

3 Comments RSS · Twitter

Jean-Daniel Dupas

The low level API has a xpc_connection_set_target_queue() function.

I don't know why there is no equivalent for NSXPCConnection.

Felix Schwarz

AppleScript was announced to be thread-safe a couple of years ago, so it should work on threads other than the main thread, too.

What was likely the problem here is that AppleScript needs a runloop, which - as far as I know - an XPC connection's internal queue just doesn't provide.

@Felix That’s interesting, thanks. The Threading Programming Guide still says that NSAppleScript is main thread–only, but the 10.6 AppleScript notes say that it “may be safely called on a non-main thread or from multiple threads,” though “trying to manipulate the same script from multiple threads at once may still be subject to race conditions, and is not recommended” (which kind of contradicts the first part). I’m not sure I believe the documentation because I recall hearing other people have problems with non-main-thread use post-10.6.

Leave a Comment