11

I have a asynchronous task like so:

dispatch_async(dispatch_get_main_queue(), ^{
     myAsyncMethodsHere;
});

Is there a way to be notified when the background task is complete?

Or to call a method upon completion?

I've read through the documentation and have looked into dispatch_after, but it seems to be more designed to dispatch the method after a certain length of time.

Thanks for the help.

Jonah
  • 4,810
  • 14
  • 63
  • 76

1 Answers1

15

From the docs:

COMPLETION CALLBACKS

Completion callbacks can be accomplished via nested calls to the dispatch_async() function. 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. For example:

 void
 async_read(object_t obj,
         void *where, size_t bytes,
         dispatch_queue_t destination_queue,
         void (^reply_block)(ssize_t r, int err))
 {
         // There are better ways of doing async I/O.
         // This is just an example of nested blocks.

         dispatch_retain(destination_queue);

         dispatch_async(obj->queue, ^{
                 ssize_t r = read(obj->fd, where, bytes);
                 int err = errno;

                 dispatch_async(destination_queue, ^{
                         reply_block(r, err);
                 });
                 dispatch_release(destination_queue);
         });
 }

Source

ACBurk
  • 4,418
  • 4
  • 34
  • 50
  • hi.. I have one doubt.. according to the documentations: dispatch_async returns immediately, and then the block executes asynchronously in the background. My doubt is .. since we are using dispatch_release after call of inner dispatch_async, is it not going to release the destination_queue before executing the inner block on it? – Devarshi Jan 18 '12 at 14:44
  • possibly, it may be better to include the release inside of the dispatch_async callback like so: dispatch_async(destination_queue, ^{ reply_block(r, err); dispatch_release(destination_queue); }); – ACBurk Jan 18 '12 at 17:11
  • I believe that the queue will be retained at the creation of the block, not when it is executed. – Ben Scheirman Jan 18 '12 at 18:51
  • The block instance is created at the time execution reaches the line it is declared. When that happens, the queue is retained. The subsequent `dispatch_release` will just release your handle on it. The block will always have a handle on it. Once the block goes away, so will the queue. – Ben Scheirman Jan 20 '12 at 02:32