简体   繁体   中英

Do we need to update UI in main thread or in main queue?

I read a lot many articles which specifies that we need to update the UI in the main thread however whenever I update my UI is always the code.

DispatchQueue.main which in return gives me the Queue not thread. How exactly I would access the thread or both are same ?

Imagine a train station where the number of the train is the same as the number of the platform that it leaves from.

So if you want the #1 train, you stand on #1 platform. You cannot get on the train without first standing on the platform. Everyone else who wants to get on this train also stands on the platform to wait for their chance to get on the train.

The train is the thread. The platform is the queue.

If you want to get on the main thread, get on the main queue.

DispatchQueue manages the execution of the code on a specific thread.

From Apple documentation:

DispatchQueue manages the execution of work items. Each work item submitted to a queue is processed on a pool of threads managed by the system.

So, when you call

DispatchQueue.main.async {
        //your code
}

This code is submitted to the main queue which in turn runs on the Main thread.

From Dispatch Queues in the Concurrency Programming Guide:

Main dispatch queue

The main dispatch queue is a globally available serial queue that executes tasks on the application's main thread. This queue works with the application's run loop (if one is present) to interleave the execution of queued tasks with the execution of other event sources attached to the run loop. Because it runs on your application's main thread, the main queue is often used as a key synchronization point for an application.

Generally, GCD maintains a pool of threads, and there is no 1-1 relationship between dispatch queues and threads. But the main queue is special: it is tied to the main thread, all items dispatched to the main queue are executed on the main thread. (The same is true for OperationQueue.main .)

Dispatching code to DispatchQueue.main (or OperationQueue.main ) ensures that it is executed on the main thread, and synchronized with other UI updates.

In this sense, the terms “execute on the main thread” and “execute on the main queue” are often used interchangeably.

//main thread

DispatchQueue.main.async
{ 
 //eg. 
 tableview.reloadData()
  // here you update your UI.
}

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