Do you really understand why you want to use
Invoke/BeginInvoke
? These methods are implemented in
System.Windows.Forms.Control
(and hence in
System.Windows.Forms.Form
in particular) and are
only useful when you call them for Control classes from a thread
other than your UI thread. You don't have to implement those methods and you really cannot do that.
Why do you need those methods? You can never call any UI methods or properties form another thread except invocation methods. The methods
Invoke
eginInvoke allow you to delegate calling of some other UI-related methods to UI class, not really calling them in your non-UI thread. Instead, the delegate instances and data needed to invoke them (such as values of parameters) are put in some queue supported by the UI thread. The UI thread picks up the elements of the queue and performs the actual call in sync with other UI calls. With
Invoke
, a calling thread is put to wait state until the call is complete by the UI thread while
BeginInvoke
returns immediately, when a call is not actually performed.
It is not really important on which UI control is used to call an invocation method; it's only important that this control is a part of currently running UI. Now,
System.Windows.Forms.Control.InvokeRequired
is not really needed when you always call some your method from non-UI thread, which is very often the case — you develop some method specially from calling from some non-UI thread.
In this case invoke is always required. You only need
InvokeRequired
to call before calling some method if your calling method is itself called from different threads: sometimes from your UI thread, sometimes from some other thread. In first case
System.Windows.Forms.Control.InvokeRequired
will always return
false
, in the second case — always
true
. If invoke is not required you still can use invocation methods, but direct call will have better performance.
One side note: for WPF UI the same mechanism can be used via the class
System.Windows.Threading.Dispatcher
with the invocation methods of the same names. This class can be used for
System.Windows.Forms
we well.
See:
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.aspx[
^],
http://msdn.microsoft.com/en-us/library/system.windows.threading.dispatcher.aspx[
^].
The remaining question is: can this or similar mechanism be used to invoke some method on an arbitrary thread. The answer is: no, unless you create such mechanism. Here is my Tips/Trick article showing how to achieve that:
Simple Blocking Queue for Thread Communication and Inter-thread Invocation[
^].
—SA