You cannot do such things. Moreover, in your case, it makes no sense at all. You need to show dialog in the UI thread. This method you used as a thread start does not contain blocking calls. You had to call it directly.
[EDIT #1]
However, I realize that you can use the thread
for some other reasons. And you may trigger showing this dialog
from this already existing thread. In this case you can do this:
class MyForm {
void ShowDialogFromAnyThread() {
System.Action show = new Action(() => {
new MessageBoxForm().ShowDialog();
});
if (InvokeRequired)
Invoke(show);
else
show();
}
}
Here, I also demonstrated how to reuse the show calls with local delegate instance.
You need to use
Invoke
, not
BegingInvoke
. I can explain.
You should clearly understand that the dialog will be shown in UI thread anyway.
[EDIT #2]
I also want to explain the role of
InvokeRequired
. Many excessively use it even it's not needed, and you might also use it. The thing is very simple: this predicate is
always false if you call a function like
ShowDialogFromAnyThread
and
always true in case of the call from any other thread. The thread is defined simply: in this context, the "UI thread" is simply the thread when this control (in this case,
Form
) was created. If calling thread is some other than that, invoke is
always required.
This way, you can also skip the check via
InvokeRequired
. If you always call this function from some other thread, you don't need to check, know that invocation is always required.
On the invocation mechanism, please see my short article
Simple Blocking Queue for Thread Communication and Inter-thread Invocation[
^].
Please also see my past answers:
Control.Invoke() vs. Control.BeginInvoke()[
^],
Problem with Treeview Scanner And MD5[
^].
—SA