Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dispatch_async a custom queue never exits block

dispatch_queue_t callerQueue = dispatch_get_current_queue();
dispatch_retain(callerQueue);
dispatch_queue_t downloadQueue = dispatch_queue_create("Download Queue",NULL);

dispatch_async(downloadQueue, 
^{
    //some code that accesses a web service
    dispatch_async(callerQueue,
    ^{
      //some code that accesses UI
    });
});
dispatch_release(downloadQueue);
NSLog(@"great successing!");

The problem is that "Great successing!" never shows up, and nothing ever happens beyond the end of the code outermost dispatch_async block. I'm not sure what I'm doing wrong but I know there is something seriously wrong with this.

like image 353
tacos_tacos_tacos Avatar asked Nov 30 '11 15:11

tacos_tacos_tacos


2 Answers

You are releasing your download queue too early. You need to wait until after it has executed the block. The dispatch_async man page suggests putting the release at the end of the block.

It is important to remember to retain the destination queue before the first call to dispatch_async(), and to release that queue at the end of the completion callback to ensure the destination queue is not deallocated while the completion callback is pending.

like image 199
JeremyP Avatar answered Sep 30 '22 18:09

JeremyP


There are a couple of problems with this code:

  1. You don't need to retain the callerQueue after creating it. It's already created with retain count of 1 and will presumably go away once you release it later. By retaining it twice, you are potentially creating a leak.

  2. You should never do UI operations on any queue other than the main queue (not the callerQueue in this case).

The rest of the code looks fine (and you don't have to release the download queue from within the block, as others are suggesting, since the dispatch_async() call will also retain it. There must be more to this code fragment we're missing (like, does the code exit right after doing the NSLog()?).

like image 35
jkh Avatar answered Sep 30 '22 16:09

jkh