In addition to the answer by Pete, some more detail:
You cannot call anything related to UI from non-UI thread. Instead, you need to use the method
Invoke
or
BeginInvoke
of
System.Windows.Threading.Dispatcher
(for both Forms or WPF) or
System.Windows.Forms.Control
(Forms only).
You will find detailed explanation of how it works and code samples in my past answers:
Control.Invoke() vs. Control.BeginInvoke()[
^],
Problem with Treeview Scanner And MD5[
^].
The call to
Control.InvokeRequired
may or may not be needed. Basically, it should be called on the control which is inserted to the same UI hierarchy as the control to be used for a call
Control.Invoke
or
Control.BeginInvoke
. That is, those controls do not have to be the same. If the calling thread is not the UI thread working with these controls,
Control.InvokeRequired
always returns true, false otherwise. As invocation methods are usually called from a non-UI thread (always true), the check is usually not required. The
Control.InvokeRequired
is needed in more rare situations where invocation is called from the method which is itself called sometimes from the correspondent UI thread (when invoke is not required) and sometimes form the some other thread (when invoke is required). In this way, the call to
Control.InvokeRequired
is needed pretty rarely.
See also more references on threading:
How to get a keydown event to operate on a different thread in vb.net[
^],
Control events not firing after enable disable + multithreading[
^].
—SA