Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why must UI elements always be created/updated from the UI thread?

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?

like image 720
MicSim Avatar asked Jul 18 '09 18:07

MicSim


People also ask

Why do you have to update the UI on the main thread?

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.

Is it a good idea to update a UI element from a background task?

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.

Can we update UI from thread?

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.

Which thread is responsible for updating the UI?

Only the Main thread, also known as the UI thread can update the UI a.f.a.i.k.


2 Answers

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.

like image 180
Jon Skeet Avatar answered Sep 22 '22 04:09

Jon Skeet


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.

like image 37
Henk Holterman Avatar answered Sep 22 '22 04:09

Henk Holterman