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[
^].
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[
^].
It is very important to avoid
Application.DoEvents
by all means and use threads itself. This call simply blocks the calling code until all the events in the event queue of the application are handled. Essentially, this code makes waits until the event queue of current application is empty. This is very dangerous because this may never happen is some code generates additional events which is a normal situation. This call is sometimes used to split the UI thread into some code with sequential logic in a loop preserving some kind of responsiveness of the application by calling
Application.DoEvents
in a loop.
Never do it. More often, such call remains in code as a result of useless attempts to change the order of event handling in case of dependency on such order.
—SA