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

I have inherited some code that has this rather unusual nested sequence. A typical paradigm would have a single dispatch in the main queue for updating the user interface. The code shown below assigns a dispatch to the main queue in 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 the nesting dispatch_async(dispatch_get_main_queue() ? This nested sequence is displayed in several places in the application. It seems to me that only one dispatch to the main queue is needed.

I think I read all the relevant questions on related topics here and through a Google search, but I did not find anyone offering two nested identical mailings.

The application works well, with an update to the user interface, as expected in the above example and elsewhere in the code.

Most of the application code uses a regular, non-nested version of the above schema, and of course it also works great.

I tend to just replace these nested calls with one send, but maybe I am missing something. Any advice would be appreciated.

+5
source share
2 answers

I cannot think of any advantages for this, and I can think of the reasons not to do this. This will delay the execution of the internal closure and also take a small amount of additional resources. (It will force the application to go through at least 2 passes through the event loop before the work item is completed.)

I think deleting nested calls is the right thing.

+2
source

Nested two dispatch_queues for the main one make no sense, the direct 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 }); }); 
0
source

Source: https://habr.com/ru/post/1273872/


All Articles