Search code examples
swiftgrand-central-dispatchnsrunloop

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.


Solution

  • 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.