In my iOS app I'm running a computationally intensive task on a background thread like this:
// f is called on the main thread
- (void) f {
[self performSelectorInBackground:@selector(doCalcs) withObject:nil];
}
- (void) doCalcs {
int r = expensiveFunction();
[self performSelectorOnMainThread:@selector(displayResults:) withObject:@(r) waitUntilDone:NO];
}
How can I use GCD to run an expensive calculation such that it doesn't block the main thread?
I've looked at dispatch_async and some options for the GCD queue choice but I'm too new to GCD to feel like I understand it sufficiently.
You use dispatch_async like suggested.
For example:
// Create a Grand Central Dispatch (GCD) queue to process data in a background thread.
dispatch_queue_t myprocess_queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0);
// Start the thread
dispatch_async(myprocess_queue, ^{
// place your calculation code here that you want run in the background thread.
// all the UI work is done in the main thread, so if you need to update the UI, you will need to create another dispatch_async, this time on the main queue.
dispatch_async(dispatch_get_main_queue(), ^{
// Any UI update code goes here like progress bars
}); // end of main queue code block
}); // end of your big process.
// finally close the dispatch queue
dispatch_release(myprocess_queue);
That's the general gist of it, hope that helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With