Why do we need to call the Main Thread for UI updates?

∥☆過路亽.° 提交于 2019-12-07 00:56:29

There is a single UI thread in (almost?) every UI framework, and all UI operations have to be performed in this. I think the main reason for this design is to prevent unexpected UI behaviour. Think of the following situation:

  • There is a list of entries in a table, call them "A" and "B"
  • "A" is currently selected
  • The user wants to delete "B"
    • The user selects "B"
    • The user presses a "Delete selected entry" button

If the user where a fast clicker/tapper, and the UI were multithreaded, then it might happen that the "select B" event handler is exectuted after the "delete selected entry" handler. Hence, "A" is still selected and would be deleted.

Therefore, typical frameworks keep track of events in a queue and process this queue in a strict order. This is what you would call "single threaded".

Therefore, if you dispatch something into the main thread, you should be aware that the time of execution is undetermined, so you must not rely on any UI state at the time of enqueuement.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!