Question

I have registered for a NSTaskDidTerminateNotification of a NSTask object. Everything works fine, but the task takes time to launch so i've moved the launching to background (with performSelectorInBackground).

  • the registration with notification center and the creation of the task itself takes place on the main thread
  • after a few seconds the task gets launched in background
  • notifications no longer arrive :(

Is there a way i could somehow adjust the code for the notifications to work again?

Was it helpful?

Solution

NSTask registers a private run-loop source to monitor the task in the run loop of the thread on which it's launched. If that thread doesn't continue to exist and run its run loop, then Cocoa can't notice that the task has terminated. If Cocoa doesn't notice it, then it can't post the notification to your observer(s).

If the only thing you're doing with -performSelectorInBackground:... is invoking the -launch method of the task, then the thread doesn't stick around nor run its run loop. (Similarly, the worker threads that service GCD queues can't be relied upon to keep existing or run their run loops.) You could invoke a more complicated method in the background which launches the task and then runs the run loop, but that shouldn't be necessary.

Are you sure that launching the task is taking any appreciable amount of time? It really shouldn't. NSTask is designed so that tasks can be created, launched, and monitored on the main thread without making it unresponsive.

OTHER TIPS

first off NSTask is not thread safe. you need to take care when using an instance of it from separate threads or avoid it entirely.

secondly as far as I can tell NSNotifications are only delivered on the thread that the notification is posted on. The notification is posted by the NSTask object itself which is apparently terminating on a secondary thread, but you have registered for the notification on the main thread. See the docs for more info.

Could you simply handle the entire task and notification sequence on the background thread?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top