Home:ALL Converter>Can we update UI from background Thread?

Can we update UI from background Thread?

Ask Time:2018-02-16T12:07:20         Author:Nisar Ahmad

Json Formatter

Hello iOS experts just to clear my concept I have a bit confusion about UI updation from Main Thread. Apple requirements are that all UI related stuff should be carried out in main Thread.So to test:

Case1: I dispatch a task to a global dispatch concurrent queue asynchronously . After some processing I update my UI stuff directly from the concurrent queue (background thread), working fine using the below code.

dispatch_queue_t myGlobalQueue;
myGlobalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(myGlobalQueue, ^{

     // Some processing
    // Update UI;
});

Case2: Than i tried the Apple required way, dispatch a block to global dispatch concurrent queue asynchronously. After some processing I update the UI stuff in Main thread using below code:

dispatch_queue_t myGlobalQueue;
myGlobalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(myGlobalQueue, ^{

    // Some processing

    dispatch_async(dispatch_get_main_queue(), ^{
        // UI Updation
    });
});

Now in both cases I am getting the same result. Now listen my questions

Questions: 1: In case1 are we still in Main Thread not in background thread ? If so than why Apple doc say:

Concurrent queues (also known as a type of global dispatch queue) execute one or more tasks concurrently, but tasks are still started in the order in which they were added to the queue. The currently executing tasks run on distinct threads that are managed by the dispatch queue. The exact number of tasks executing at any given point is variable and depends on system conditions.

Now if we are on Main Thread than this is a contradiction with the bold part of Apple Doc.

2: In Case1 if we are in background thread, than why Apple require to get Main Thread for UI Updation, Even though we can update UI from background Thread too?.

Kindly read my question fully and suggest me if I am doing something wrong. Your help and time would be greatly appreciated.

Author:Nisar Ahmad,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/48819925/can-we-update-ui-from-background-thread
yy