Frage

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.

War es hilfreich?

Lösung

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.

Andere Tipps

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");
            }
        }
    );
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top