I want to have one call occur asynchronously, the equivalent of:
doThisInASecondThreadThenHaveThisThreadDisappear:@selector(myMethod);
What is the Grand Central Dispatch call to accomplish this? I'm new to it and I get lost with all the complex stuff with queueing. I understand things that can be achieved with that, but for this simple case (that I currently care about) I'm just lost
GCD is built on top of threads. Under the hood, it manages a shared thread pool. With GCD, you add blocks of code or work items to dispatch queues and GCD decides which thread to execute them on. As you structure your code, you'll find code blocks that can run simultaneously and some that should not.
To summarize, DispatchQueue. async allows you to schedule work to be done using a closure without blocking anything that's ongoing. In most cases where you need to dispatch to a dispatch queue you'll want to use async .
You attach multiple work items to a group and schedule them for asynchronous execution on the same queue or different queues. When all work items finish executing, the group executes its completion handler. You can also wait synchronously for all tasks in the group to finish executing.
Dispatch queues are FIFO queues to which your application can submit tasks in the form of block objects. Dispatch queues execute tasks either serially or concurrently. Work submitted to dispatch queues executes on a pool of threads managed by the system.
dispatch_queue_t queue = dispatch_queue_create("queueName", NULL);
dispatch_async(queue, ^(void) {
// code to execute here
});
dispatch_release(queue);
Or if you need to use the main thread:
dispatch_async(dispatch_get_main_queue(), ^(void) {
// code to execute here
});
Here's a quick code example
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0);
dispatch_async(queue, ^{
// Stuff to do on another thread
// Mostly heavy calculations
dispatch_async(dispatch_get_main_queue(), ^{
// Stuff to do on main thread
// Mostly UI stuff
});
});
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