Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is only the UI thread allowed to modify the UI?

I know that if I am modifying a control from a different thread, I should take care because WinForms and WPF don't allow modifying control's state from other threads.

Why is this restriction in place?

If I can write thread-safe code, I should be able to modify control state safely. Then why is this restriction present?

like image 207
TalentTuner Avatar asked Sep 25 '10 15:09

TalentTuner


3 Answers

Several GUI frameworks have this limitation. According to the book Java Concurrency in Practice the reason for this is to avoid complex locking. The problem is that GUI controls may have to react to both events from the UI, data binding and so forth, which leads to locking from several different sources and thus a risk of deadlocks. To avoid this .NET WinForms (and other UIs) restricts access to components to a single thread and thus avoids locking.

like image 125
Brian Rasmussen Avatar answered Oct 18 '22 06:10

Brian Rasmussen


In the case of windows, when a control is created UI updates are performed via messages from a message pump. The programmer does not have direct control of the thread the pump is running on, therefore the arrival of a message for a control could possibly result in the changing of the state of the control. If another thread (that the programmer was in direct control of) were allowed to change the state of the control then some sort of synchronization logic would have to be put in place to prevent corruption of the control state. The controls in .Net are not thread safe; this is, I suspect by design. Putting synchronization logic in all controls would be expensive in terms of designing, developing, testing and supporting the code that provides this feature. The programmer could of course provide thread safety to the control for his own code, but not for the code that is in .Net that is running concurrently with his code. One solution to this issue is to restrict these types of actions to one thread and one thread only, which makes the control code in .Net simpler to maintain.

like image 20
Steve Ellinger Avatar answered Oct 18 '22 06:10

Steve Ellinger


.NET reserves the right to access your control in the thread where you created it at any time. Therefore accesses that come from another thread can never be thread safe.

like image 37
Ben Voigt Avatar answered Oct 18 '22 04:10

Ben Voigt