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?
While an animation or screen update is occurring, the system tries to execute a block of work (which is responsible for drawing the screen) every 16ms or so, in order to render smoothly at 60 frames per second. For the system to reach this goal, the UI/View hierarchy must update on the main thread.
You're updating the UI from a background thread. Don't do that. But the runtime is not required to provide a safety system that prevents or detects your error. It is not required to produce an error when you do something that you shouldn't be doing in the first place.
However, note that you cannot update the UI from any thread other than the UI thread or the "main" thread. To fix this problem, Android offers several ways to access the UI thread from other threads. Here is a list of methods that can help: Activity.
Only the Main thread, also known as the UI thread can update the UI a.f.a.i.k.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With