1

Eventually I have used asyncAfter feature in swift with no time, and it does some delay and seems different with normal code.

Code with async:

DispatchQueue.main.asyncAfter(deadline: .now() + 0.0 , execute: {
    self.updateUI()
})

Normal code:

self.updateUI()

Similar problem with perform selector also.

self.performSelector("onFlip", withObject: nil, afterDelay: 0)

Is that delay is caused because of creating new thread?

Saranjith
  • 11,242
  • 5
  • 69
  • 122

2 Answers2

1

This is expected.

DispatchQueue.main.asyncAfter(deadline: .now() + 0.0 , execute: {
    self.updateUI()
})

Is essentially the same as

DispatchQueue.main.async {
    self.updateUI()
}

which also won't execute immediately due to the fact that you dispatch the code to the main thread asynchronously. Due to the async dispatch, the code inside the closure won't be executed immediately, only on the next runloop of main, which might result in a measurable delay .

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
1

asyncAfter doesn't create a new thread, since you are dispatching on the main queue, which will use the main thread, but neither will it execute the dispatched code immediately.

You have submitted a block of code to run on the main queue, so some time will elapse before the runloop can execute that code; particularly if the asyncAfter is being called on the main thread.

Paulw11
  • 108,386
  • 14
  • 159
  • 186