简体   繁体   中英

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.

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.

Nesting two dispatch_queues for the main doesn't make any sense , the straight forward way is that

   dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

 // perform long task here 

 dispatch_async(dispatch_get_main_queue(), ^(){

  //Add method, task you want perform on mainQueue
 //Control UIView, IBOutlet all here

});  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM