On Sun, Dec 16, 2012, at 12:04 PM, Tamas Nagy wrote:
> Thanks for the approach Kyle, but dispatch_async performs asynchronously,
> so it should not block the main thread. I fallback to
> performSelectorOnMainThread: method in my app, but the dispatch way is a
> bit straightforward in my opinion. I'll fill a rdar on this. 

It's not the dispatch_async() call that's blocking the main thread. It's
the block you've enqueued.

Imagine that instead of -runModal, we had this:

void DoTheThing() {
  dispatch_async(dispatch_get_main_queue(), ^{
    /* Let's call this POINT A. */
    int result = GetTheResult();

    /* Let's call this POINT C. */
    NSLog(@"Result: %ld", result);
  });
}

int GetTheResult() {
  /* We've got to do some prep work which will take a long time. Let's
  show a spinner. */
  ShowTheSpinner();

  /* But we want to let the user interact with the dialog while we're
  doing the prep work, so let's do it on a background queue. */
  dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,
  0),^{
    DoABunchOfWork();

    /* We're done! We need to hide the spinner from the main thread */
    dispatch_async(dispatch_get_main_queue(), ^{
      /* Let's call this POINT B. */
      HideTheSpinner();
    });
  }

  /* While the work is being done in the background, run the main
  thread's runloop reentrantly until the user dismisses the dialog. We
  don't return from this function until the user chooses one of those
  buttons. */
  while (TheUserHasntHitCancelOrOk)
    [[NSRunLoop currentRunLoop] runMode:NSRunLoopCommonModes
    beforeDate:[NSDate distantFuture]];

  return UserCanceled ? 0 : 1;
}

As you can see, POINT B needs to happen on the main thread, so it is
wrapped inside a block that's enqueued on the main queue. But because
GetTheResult() doesn't return until the user clicks Cancel or OK, POINT
B can't execute because POINT A is still executing! The very nature of
queues says we need to get to POINT C before POINT B can execute.

--Kyle Sluder
_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Reply via email to