Re: NSTask dilema...
Re: NSTask dilema...
- Subject: Re: NSTask dilema...
- From: Ken Thomases <email@hidden>
- Date: Wed, 31 Mar 2010 13:35:00 -0500
On Mar 31, 2010, at 1:21 PM, Jean-Nicolas Jolivet wrote:
> I have to run a bunch of NSTasks and I'm not sure to proceed considering I want to be able to update the UI when a task is completed, and I want the process to be as fast as possible (obviously)...
> - I tried launching the tasks on the main thread but it locks up my UI and I can't update my progress bar...
Then you're doing it wrong. ;)
NSTask provides for completely asynchronous operation. All you have to do is avoid the synchronous methods (e.g. waitUntilExit).
Create the task; set it up; register some controller object as an observer of its termination notification; if you're performing I/O, register as an observer of the file handles' read-in-background notifications; launch the task; start the background reads from the file handles; have the controller retain the task object; return to the event loop.
As relevant events occur (task terminates, data is read from the file handles), your observer will be notified. Take the appropriate action.
Once the task has terminated _and_ the file handles indicate end-of-file (zero-length data objects), then you should unregister from the notifications and release the task object.
> - If I try to dispatch each task in the background using GCD (dispatch_group_async and the global queue), it works just fine (and it's really fast too!), but I can't use NSTask's waitUntilExit (I know NSTask is not thread safe but I'm not sharing any NSTasks between threads...however, using waitUntilExit makes the app crash...badly...)... so basically I can use GCD to dispatch the NSTasks but then there's no way to be notified when the task are completed....(obviously I'm not receiving the NSTaskDidTerminateNotification notification either since each tasks are launched in a different thread)
I'm not exactly sure what's going on there, but NSTask can be used from background threads (although it's not necessary, as explained above). Using it from GCD's threads, though, is iffy at best. Be warned that being notified of NSTask's termination (or NSFileHandle's background reads) requires that the runloop of the originating thread is run. -[NSTask waitUntilExit] does run the runloop, so that can take care of it for you, although that has to be invoked on the same thread as the NSTask was launched (and maybe created?).
Regards,
Ken
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden