views:

179

answers:

3

The title says it all: 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?

+8  A: 

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.

Jon Skeet
wouldn't it be easier for the framework to do the check and marshall the call itself instead of taking the risk to have somebody calling it in an unsafe way in the first place? the .Net framework could have done it for us at least...
zaladane
I would say no. If you make a call to a Textbox's Text property, right now it's a pretty quick set. If you push the handling to the framework, *every* call is going to be bound by that penalty, even though the majority of the updates are coming from the UI thread itself.
jasonh
@zaladane: I think it might not be so easy to (automatically) determine when code is required to run on the UI Thread. I do would favor a construct in the language (perhaps a bit like the unsafe keyword) to run a specific piece of code on the UI Thread. That would be a bit easier to read then the Dispatcher code.
Zyphrax
@Zyphrax: I thought determining it was the easy part. You make a call to the Form's InvokeRequired property and if it's true, you call BeginInvoke or Invoke to a method that does what you need to do. Otherwise, you call that method directly.
jasonh
Of course, that assumes that you're using the .NET Framework. Still, if the .NET Framework can make it as easy as calling a property, it's not that hard is it?
jasonh
@jasonh: The problem is that checking whether or not invoke is required can be expensive - you don't want that happening for every mouse movement etc if you already know you're in the right thread.
Jon Skeet
+5  A: 

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.

Henk Holterman
+3  A: 

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.

Simon Nickerson