INs
INs

Reputation: 3159

Why i should call Control.Invoke from non-ui thread?

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?

Upvotes: 0

Views: 273

Answers (2)

Adam Houldsworth
Adam Houldsworth

Reputation: 64517

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.

Upvotes: 1

Alex F
Alex F

Reputation: 43331

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.

Upvotes: 1

Related Questions