How does Dispatch.main.async “update the UI”?

后端 未结 2 777
说谎
说谎 2021-01-27 06:38

I\'ve been using Swift for a little while and GCD still confuses me a bit.

I\'ve read:

https://www.raywenderlich.com/60749/grand-central-dispatch-in-depth-part-1

2条回答
  •  长发绾君心
    2021-01-27 07:27

    FYI the reason that all of the UI code needs to go on the main thread is because drawing is a (relatively in CPU time) long and expensive process involving many data structures and millions of pixels. The graphics code essentially needs to lock a copy of all of the UI resources when its doing a frame update, so you cannot edit these in the middle of a draw, otherwise you would have wierd artifacts if you went and changed things half way through when the system is rendering those objects. Since all the drawing code is on the main thread, this lets he system block main until its done rendering, so none of your changes get processed until the current frame is done. Also since some of the drawing is cached (basically rendered to texture until you call something like setNeedsDisplay or setNeedsLayout) if you try to update something from a background thread its entirely possible that it just won't show up and will lead to inconsistent state, which is why you aren't supposed to call any UI code on the background threads.

提交回复
热议问题