Question

I conceptional question for background tasks.

I need to handle a time consuming task in the background. The task is triggered by a slider action. Right now with running the task on the main thread the slider wont react since the first change of the slider value triggers the long calculation. This is bad for the user interaction.

I would like to put the task in the background using NSOperation but I do not know how to handle the fast changing slider values. Is there a way to immediately stop/restart the started background task when the input values will change again? One option might be to work with NSOperationQueue and removing not started outdated tasks in the queue as long as the slider is activated?!?

Thanks

Was it helpful?

Solution

You can use main thread notification queue with NSPostWhenIdle style notifications (https://developer.apple.com/library/ios/documentation/cocoa/Conceptual/Notifications/Articles/NotificationQueues.html#//apple_ref/doc/uid/20000217-115535) to start the background task.

The background task can be done by starting NSOperation on NSOperationQueue. NSOperation supports cancellation, your background task will need to check isCancelled flag periodically. If user resumes sliding while the background task is in progress you will need to cancel the task and post NSPostWhenIdle notifications again.

OTHER TIPS

You basically need to let your thread know about changes in main UI thread, if I understood your question correctly. You can do something like that:

  1. In the main thread create public property with value of a slider. Pass pointer to the main controller/view where this property is exposed to the worker thread. This way worker thread can read that value when it needs.

  2. In worker thread make your calculation in a loop or somehow else check that value quite often and change logic or restart calculation if value has been changed.

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