Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of nesting dispatch_async(dispatch_get_main_queue()^{}) ?

I've inherited some code that has this rather unusual nested sequence. The usual paradigm would have a single dispatch to the main queue to update the UI. The code, shown below, nests a dispatch to the main queue within another dispatch to the main queue.

- (void)viewDidLoad
{
// Setup some data
// Adjust UI

 dispatch_async(myBackgroundQueue, ^{
   while(Do_some_time_consuming_work) {

     // Time consuming work goes here

     if (things_are_going_slowly) {

        dispatch_async(dispatch_get_main_queue(), ^{    // <- one of these two seems redundant
          dispatch_async(dispatch_get_main_queue(), ^{  // <- one of these two seems redundant

            stillWorkingLabel.hidden = NO; //Let user know the work is still ongoing
          });
        });
     )

   // Finish time-consuming work
   }

  });

}

What is the purpose, if any, of nesting dispatch_async(dispatch_get_main_queue()? This nested sequence shows up in several places in the app. It seems to me that only one dispatch to the main queue is needed.

I think I've read all of the relevant questions on related topics here and via Google search, but I haven't found anyone suggesting nesting two identical dispatches.

The app works well, with the UI updating as expected in the above example and in other places in the code.

Most of the app's code uses the usual non-nested version of the above scheme, and of course it also works just fine.

I'm inclined to just replace these nested calls with a single dispatch, but maybe I'm missing something here. Any advice would be appreciated.

like image 894
nyDavid21 Avatar asked Oct 28 '22 22:10

nyDavid21


1 Answers

I can't think of a single advantage to doing this, and can think of reasons not to. It will delay the execution of the inner closure, as well as taking a small amount of additional resources. (It's going to force the app to go through at least 2 passes through the event loop before the work item gets executed.)

I think removing the nested calls is the right thing to do.

like image 52
Duncan C Avatar answered Nov 15 '22 06:11

Duncan C