Wednesday, 9 January 2019

Tips for using DispatchQueue

Tips

  • UI operations should only happen in main queue. DispatchQueue.main.async {}
  • API calls: DispatchQueue(label: "api-queue").async {}
  • Check current queue: print("\(#function) is running at \(Thread.current)")
  • Check is on main thread: Thread.current.isMainThread
  • DispatchQueue.main.sync{} will cause crash
  • Delay DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {}

  • Tasks in DispatchQueue.main.async from main thread will still be executed in main thread after all the other execution finished. For example:


The output will be:



Different Quality of Service in Apple's documentation


     DispatchQueue(label: "userInteractive", qos: .userInteractive)




No comments:

Post a Comment