问题
Why must UI elements always be created/updated from the UI thread?
In (almost?) all programming languages UI elements may be safely accessed/modified only from the UI thread. I understand that it's a standard concurrent access and synchronization problem, but is it really necessary? Is this behaviour imposed by the programming languages or by the operating system? Are there any programming languages where this situation is different?
回答1:
It's imposed by the graphics framework - which is often (but not always) supplied by the operating system.
Basically, making everything "properly threadsafe" is inefficient. While it's certainly a pain to have to marshal calls back to the UI thread, it allows the UI thread itself to process events extremely quickly without having to worry about locking etc.
回答2:
It would be very costly (slow) to make the entire UI thread-safe. Better to put the burden on the programmer to sync in the (relatively rare) occasion a Thread needs to update the UI.
回答3:
It's because the UI framework has been designed that way. It is theoretically possible to design a UI framework which is truly multi-threaded, but it's hard to avoid deadlocks.
Graham Hamilton wrote a nice article about this with reference to Swing, the main Java UI framework.
来源:https://stackoverflow.com/questions/1148225/why-must-ui-elements-always-be-created-updated-from-the-ui-thread