NSOperations Queue and Exit Processing Application

I am going to create a series of NSOperation and run them in the queue.

All of them will be sequentially launched in turn.

These operations will extract data from the Internet and create and store basic data-driven objects.

How do I handle a situation when an application exits? Like operations performed on separate threads, how can I make the main thread wait until the current operation is “safe” to exit? There are situations when I am glad that threads (operations) exit before they end, because when the application starts, the application will continue and pick up where it stopped.

Thank you very much,

Mike

+4
source share
2 answers

Create your operations so that they check their isCancelled property at appropriate safe times (at the beginning, after the completion of one stage of the operation, etc.) and exit at that moment. In applicationWillTerminate send your operational queue a -cancelAllOperations message and follow this -waitUntilAllOperationsAreFinished message. This will be blocked until all operations in the queue are completed. This should not slow down the output of the application if all operations handle isCancelled correctly.

Beware that -waitUntilAllOperationsAreFinished when called from applicationWillTerminate will be blocked in the main thread. If any of your operations performs a main thread selector, your application freezes at that point.

+5
source

Your application will be forced to exit if it is not completed on its own within a certain time. Therefore, waiting for some data to appear from the Internet may not be a good idea.

But you have already given yourself the answer. Just make atomic operations by design. I mean that your operations must either complete the task (load + save data) or run it again the next time it starts. Make sure that all temporary job data is canceled if the application is closed before the job is completed.

+2
source

All Articles