Or Asynchronous design patterns using gcd queue and Blocks

If you have cpu intensive work to do then you should not do that on the main thread. But you then need to remember to update the UI on the main thread. So you have one block that does the work not on the main thread, and this then contains another block which then updates the UI on the main thread. In the following example render thumbnails is done on the main thread.

// Main thread.
dispatch_queue_t queue;
queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
void (^offLoadWorkBlock)(void) = 
  [self renderThumbnails];
  void (^updateUIOnMainThreadBlock)(void) = 
    [self.thumbnailView setNeedsDisplay:YES];
  dispatch_async(dispatch_get_main_queue(), updateUIOnMainThreadBlock);
dispatch_async(queue, offLoadWorkBlock);

Don’t allow too many background threads to become blocked.

If for example you want to download lots of images from the internet then you should use dispatch IO, this is demonstrated in the Asynchronous design patterns with blocks, GCD and ARC 2012 WWDC session video and is described about 40 minutes into the video.

dispatch_get_main_queue() is a useful method for getting the main queue.

Tags: , , , , ,