Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In WinForms, why can't you update UI controls from other threads?

I'm sure there is a good (or at least decent) reason for this. What is it?

like image 631
Larsenal Avatar asked Aug 13 '08 20:08

Larsenal


People also ask

Can we update UI from thread?

Worker threads 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 can update the user interface?

Android Thread Updating the UI from a Background Thread This poses a problem, as only the main thread can update the UI. The solution is to use the runOnUiThread() method, as it allows you to initiate code execution on the UI thread from a background Thread.

Can only be accessed from the UI thread?

Security isn't the only UI thread is the only thread that can access the Views. The main reason is that the code behind the views probably isn't thread safe. This means that there are no guarantees that data won't get corrupted if you have multiple threads reading and writing to common variables.

What is InvokeRequired in c#?

Gets a value indicating whether the caller must call an invoke method when making method calls to the control because the caller is on a different thread than the one the control was created on. public: property bool InvokeRequired { bool get(); }; C# Copy.


1 Answers

I think this is a brilliant question - and I think there is need of a better answer.

Surely the only reason is that there is something in a framework somewhere that isn't very thread-safe.

That "something" is almost every single instance member on every single control in System.Windows.Forms.

The MSDN documentation for many controls in System.Windows.Forms, if not all of them, say "Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe."

This means that instance members such as TextBox.Text {get; set;} are not reentrant.

Making each of those instance members thread safe could introduce a lot of overhead that most applications do not need. Instead the designers of the .Net framework decided, and I think correctly, that the burden of synchronizing access to forms controls from multiple threads should be put on the programmer.

[Edit]

Although this question only asks "why" here is a link to an article that explains "how":

How to: Make Thread-Safe Calls to Windows Forms Controls on MSDN

http://msdn.microsoft.com/en-us/library/ms171728.aspx

like image 97
Brian Ensink Avatar answered Sep 24 '22 07:09

Brian Ensink