1

My MessageBox is async, but how can I return DialogResult?

Here is my code:

class AsyncMessageBox
{
    private delegate void ShowMessageBoxDelegate(string strMessage, string strCaption, MessageBoxButtons enmButton, MessageBoxIcon enmImage);
    // Method invoked on a separate thread that shows the message box.
    private static void ShowMessageBox(string strMessage, string strCaption, MessageBoxButtons enmButton, MessageBoxIcon enmImage)
    {
        MessageBox.Show(strMessage, strCaption, enmButton, enmImage);
    }
    // Shows a message box from a separate worker thread.
    public void ShowMessageBoxAsync(string strMessage, string strCaption, MessageBoxButtons enmButton, MessageBoxIcon enmImage)
    {
        ShowMessageBoxDelegate caller = new ShowMessageBoxDelegate(ShowMessageBox);
        caller.BeginInvoke(strMessage, strCaption, enmButton, enmImage, null, null);
    }
}
KotkaZ
  • 41
  • 1
  • 1
  • 8
  • 2
    Why on earth do you need asynchronous message box? – Dennis Jan 17 '16 at 19:41
  • 1
    While I have no Idea about the usage of async message box, but in the case that you want to show a non-blocking messagebox and use the dialogresult you can use `Task.Run` – Reza Aghaei Jan 17 '16 at 19:47
  • I am using asynchronous message box in online program. This helps to keep connection alive. For example if someone disconnect then it shows messagebox. If someone disconnect more then it shows another messagebox. Well it's hard to explain, but I got answer. – KotkaZ Jan 17 '16 at 19:56

1 Answers1

17

If you want to use the dialog result of a non-blocking message box and perform a job based on the result:

Task.Run(() =>
{
    var dialogResult=  MessageBox.Show("Message", "Title", MessageBoxButtons.OKCancel);
    if (dialogResult == System.Windows.Forms.DialogResult.OK)
        MessageBox.Show("OK Clicked");
    else
        MessageBox.Show("Cancel Clicked");
});

Note:

  • The code after Task.Run immediately runs regardless of messagebox.
Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398