Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between DispatchQueue.main.async and Dispatch.main.asyncAfter(.now(),{})

Is there a difference between DispatchQueue.main.async and Dispatch.main.asyncAfter(.now(),{})

My question is specifically about asyncAfter with .now() as the delay time.

The second question is if both methods allow the current UI thread to end before executing the closure in the next runloop?

I find that displaying an alert using UIAlertController in the closure of the former causes some erratic behavior. And with the latter, together with a delay of about 0.3 seconds, it works well.

like image 658
Mark Kang Avatar asked Oct 17 '25 20:10

Mark Kang


2 Answers

There is no difference if you chooses to use asyncAfter with .now. Here is the proof. Both function should start executing immediately after getting called

enter image description here

like image 58
Fangming Avatar answered Oct 19 '25 09:10

Fangming


There is no difference. I tested by invoking it 100 times, and the callbacks are executed in the same order they're enqueued.

I further tested by having 100 queues, to see how it behaves with parallelism, and the callbacks are still executed in the same order as they are enqueued. So, the conclusion is that asyncAfter(.now()) is same as async:

func testOneThread() {
  var lastCallbackRun = 0

  for i in 1...100 {
    DispatchQueue.main.asyncAfter(.now()) {
      assert(lastCallbackRun < i)
      lastCallbackRun = i
      if i == 100 {
        NSLog("done")
      }
    }
  }
}

func testAsync() {
  for _ in 0...100 {
    let q = DispatchQueue(label: "whatever")
    q.async(execute: testOneThread)
    Unmanaged<DispatchQueue>.passRetained(q)
  }
}

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

  func application(_ application: UIApplication,
                   didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    testAsync()
    // The rest of it.
  }
}
like image 45
Kartick Vaddadi Avatar answered Oct 19 '25 11:10

Kartick Vaddadi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!