Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's wrong with calling Invoke, regardless of InvokeRequired?

I've seen the common setup for cross threading access to a GUI control, such as discussed here: Shortest way to write a thread-safe access method to a windows forms control

All the web hits I found describe a similar thing.

However, why do we need to check InvokeRequired? Can't we just call Invoke directly?

I assume the answer is no, so my real question is 'why'?

like image 818
MattH Avatar asked Apr 14 '09 11:04

MattH


Video Answer


2 Answers

From non-UI threads we can't touch the UI - very bad things can happen, since controls have thread affinity. So from a non-UI thread we must (at a minumum) call Invoke or BeginInvoke.

For UI-threads, however - we don't want to call Invoke lots of time; the issue is that if you are already on the UI thread, it still has the unnecessary overhead of sending a message to the form's pump and processing it.

In reality, in most threading code you know you expect a specific method to be called on a non-UI thread, so in those cases, there is no additional overhead: just call Invoke.

like image 177
Marc Gravell Avatar answered Sep 22 '22 16:09

Marc Gravell


InvokeRequired basically tells you if you're executing on the right thread or not. If you're not on the correct thread, you need to marshal the task to the correct thread otherwise you don't. Hence the need for the check.

like image 42
Brian Rasmussen Avatar answered Sep 19 '22 16:09

Brian Rasmussen