The question is not clear and full of unrelated information while some related information is probably missing. Basically, all the calls to any UI methods/properties should be done only from the UI thread.
So, if you want to cause showing or hiding the form safely from any thread, you should do this:
static void ShowHideForm(Form form, bool show ) {
if (form.InvokeRequired) {
form.Invoke(new Action<Form, bool>((formInstance, isShow) => {
if (isShow)
formInstance.Show();
else
formInstance.Hide();
}), form, show);
} else {
if (show)
form.Show();
else
form.Hide();
}
}
Instead of
Invoke
which waits for processing of the delegate in the UI thread event cycle, you can use non-bloking
BeginInvoke
which will return immediately when a delegate instance and parameters for its call are posted to the queue of the UI thread, see my references below.
The check of
InvokeRequired
is not really required: this code will work if only the invocation method is used (first branch under this condition). Non-invocation branch (direct call) will be just more effective when called from UI thread. There is another case when only an invocation part is needed: when you are sure that the code above will be called only from a non-UI thread. Again, it will work from any thread, but it would be less effective if called from (the same) UI thread.
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[
^].
—SA