While the selected answer provides a nice way of displaying the MessageBox
from an asynchronous thread, it doesn't handle the case where you want to retrieve the DialogResult
from that particular MessageBox
being shown.
If you are looking to return a DialogResult
from the invoked MessageBox
displayed on top of the Form
. Then you need to use the Func
delegate instead of the Action
delegate.
Action
delegates always return void while Func
has a return value.
Here is a little method that I devised to handle this particular scenario:
private DialogResult BackgroundThreadMessageBox(IWin32Window owner, string text)
{
if (this.InvokeRequired)
{
return (DialogResult) this.Invoke(new Func<DialogResult>(
() => { return MessageBox.Show(owner, text); }));
}
else
{
return MessageBox.Show(owner, text);
}
}
Although this isn't typically considered best practice or design it will work in a pinch.