Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use Grand Central Dispatch to kick off one asynchronous call?

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

like image 493
Nektarios Avatar asked Jul 26 '11 12:07

Nektarios


People also ask

How does Grand Central Dispatch work?

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.

What is Dispatch main async?

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 .

How does a dispatch group work?

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.

What is a dispatch queue?

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.


2 Answers

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
});
like image 131
hwaxxer Avatar answered Sep 23 '22 02:09

hwaxxer


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
    });                    
});    
like image 32
Tudor Avatar answered Sep 23 '22 02:09

Tudor