简体   繁体   中英

Why run loop is needed when using DispatchQueue.main.async in mac command line tool in swift?

I found Apple's document to understand why i should use run loop to implement task in main dispatch queue.

According to Apple docs ,

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.

but still, i can't understand 'why' run loop is needed. it sounds like 'it needs run loop because it needs run loop'. I will very appreciate it if someone explain me about this. Thank you.

DispatchQueue.main.async is when you have code running on a background queue and you need a specific block of code to be executed on the main queue.

In your code, viewDidLoad is already running on the main queue so there is little reason to use DispatchQueue.main.async.

But isn't necessarily wrong to use it. But it does change the order of execution.

async closure is queued up to run after the current runloop completes.

why i should use run loop to implement task in main dispatch queue

Normally, you don't, because you are already using one!

In an application project, there is a main queue run loop already . For example, an iOS app project is actually nothing but one gigantic call to UIApplicationMain, which provides a run loop.

That is how it is able to sit there waiting for the user to do something. The run loop is, uh, running. And looping.

But in, say, a Mac command line tool, there is no automatic run loop. It runs its main function and exits immediately. If you needed it not to do that, you would supply a run loop.

i can't understand 'why' run loop is needed

Generally, a run loop is not needed for command line apps. You can use run loops if you have a special need for one (eg you have some dynamic UI that is performing some tasks while you wait for user input), but the vast majority of command line apps don't require run loops.

As the docs say:

A run loop is an event processing loop that you use to schedule work and coordinate the receipt of incoming events. The purpose of a run loop is to keep your thread busy when there is work to do and put your thread to sleep when there is none.

So, if you need to have your app wait for some incoming events or you're dispatching tasks asynchronously between queues, then, fine, employ run loops, but otherwise, don't bother. Most command line apps don't need to use run loops at all.

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