views:

32

answers:

2

Why i should call Control.Invoke from non-ui thread? As i know any manipulations with control are the messages to control. So when i call, for example TextBox.Text = "text", it will produce message SendMessage(TextBox.Hanlde...). That message will be queued into UI thread message queue and dispatched by UI thread. Why i have to call invoke, even it will produce the same message?

+1  A: 

Because you cannot directly access UI controls from threads other than the thread they were created on. Control.Invoke will marshal your call onto the correct thread - allowing you to make a call from another thread onto the UI thread without needing to know yourself what the UI thread is or how to perform the marshalling.

Update: to answer your question, you don't have to use Control.Invoke - if you have code to marshal your call onto the correct thread and post a message to the message pump - then use that. This, however, is known as re-inventing the wheel. Unless you are doing something that changes the behaviour.

Adam
I know how works Control.Invoke, i ask why i can't call directly. Anyway TextBox.Text will put message to UI thread message queue
INs
+1  A: 

There are two reasons MS developers made this restriction:

  1. Some UI functions have access to thread-local storage (TLS). Calling these functions from another thread gives incorrect results on TLS operations.

  2. Calling all UI-related functions from the same thread automatically serializes them, this is thread-safe and doesn't require synchronization.

From our point of view, we just need to follow these rules.

Alex Farber
Ok, how about STA activex components, maybe some controls is COM+ objects?
INs
Sorry, I didn't get your point. We are talking about Windows Forms controls. Maybe some of them use COM internally, but this is not part of their public interface.
Alex Farber
I mean, this restriction also guarantee executing UI COM objects from STA threads.
INs
Maybe. I didn't think about COM STA, this is one more advantage (for Windows Forms developers, not users).
Alex Farber