pvllnspk
pvllnspk

Reputation: 5767

create a custom sequential global dispatch queue

In many places in my app I use the next code to perform background tasks and notify the main thread:

dispatch_queue_t backgroundQueue = dispatch_queue_create("dispatch_queue_#1", 0);
    dispatch_async(backgroundQueue, ^{

   dispatch_async(dispatch_get_main_queue(), ^{


        });
    });

Is it possible to create a backgroundQueue in one place (where does the best way?) and use it later? I know about the system global queue, but ordering is important for me.

Upvotes: 22

Views: 22655

Answers (4)

AllanXing
AllanXing

Reputation: 173

queue = dispatch_queue_create("com.something.myapp.backgroundQueue", 0);

Preceding is Serial Queue,if you want create concurrent queue,you can use DISPATCH_QUEUE_CONCURRENT.

In iOS 5 and later, you can create concurrent dispatch queues yourself by specifying DISPATCH_QUEUE_CONCURRENT as the queue type.

dispatch_queue_t queue = dispatch_queue_create("downLoadAGroupPhoto",
                                                   DISPATCH_QUEUE_CONCURRENT);

Upvotes: 1

Ankit Goyal
Ankit Goyal

Reputation: 3049

  dispatch_async( dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                //back ground thread

                 dispatch_async( dispatch_get_main_queue(), ^{
                     // main thread
                      });
                });

Upvotes: -7

Catfish_Man
Catfish_Man

Reputation: 41801

Something like this should work fine:

dispatch_queue_t backgroundQueue() {
    static dispatch_once_t queueCreationGuard;
    static dispatch_queue_t queue;
    dispatch_once(&queueCreationGuard, ^{
        queue = dispatch_queue_create("com.something.myapp.backgroundQueue", 0);
    });
    return queue;
}

Upvotes: 41

JeffRegan
JeffRegan

Reputation: 1322

You could also us an NSOperationQueue and push operations to it. To make sure the operations don't run out of order, you can set isConcurrent to NO.

Upvotes: 0

Related Questions