In visual C#, a exception occur, call a message box to display error message. How can I continue to execute my program without waiting the message box be closed.
-
1Do you have to display a message box? Why not log the error to the console or a text file and read it from there? Otherwise see http://stackoverflow.com/questions/10634663/messagebox-that-allows-a-process-to-continue-automatically – KJ3 Mar 27 '14 at 01:13
-
1You should log the exception, then _fix the problem_. Exceptions usually mean your code is broken. So fix it. – John Saunders Mar 27 '14 at 02:09
2 Answers
Instead of using MessageBox.Show
, you can make your own error message Form
and show it in a non-modal way, using the Form.Show()
method. This will allow your UI thread to keep on rolling.
Of course this also mean you will have to set up a few things yourself like size, text alignment and the likes. But that shouldn't be too much trouble if you really just want to use it for one task.
I have to say though, I find your approach quite strange. Normally when an error occurs and you want the user to be informed of it, you'd want the app to hold until the message box is closed. Not doing so may lead into lots of unsuspected problems. For example: what happens if another error occurs while an error is already showing?
If you need a particular task to complete while the UI thread is on hold, I would strongly suggest that you look into doing it in a new thread if possible. This ought to give you what you want while keeping the end user experience up to expectations.

- 10,211
- 6
- 43
- 75
If you absolutely need to run it in a non-blocking manner you can initialize the message box in a separate thread:
Task.Run(() => MessageBox.Show("Test"));
Additionally, if you have to relay on the result of the dialog (Ok/Cancel) than probably the whole method has to be run in the new thread.
Task.Run(
() =>
{
if (MessageBox.Show("Test", "test", MessageBoxButtons.OkCancel) == DialogResult.OK)
{
MessageBox.Show("Ok");
}
else
{
MessageBox.Show("Cancel");
}
}
);

- 8,408
- 6
- 48
- 68
-
-
Definitely it's not advised. I rather presented it as a last resort if you absolutely must display the message box in a non-blocking manner. – PiotrWolkowski Mar 27 '14 at 13:52
-
Do anyone of you think about any particular risks with this code snippet? Or is it just a warning in general not to do UI in other threads? I don't see how your suggestion can cause any issues as long as it does nothing more than display the modal? – Alex Telon Apr 10 '18 at 11:31