C# 如何制作 returns DialogResult 的异步 MessageBox?

C# How to make async MessageBox that returns DialogResult?

我的 MessageBox 是异步的,但是我如何 return DialogResult?

这是我的代码:

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);
    }
}

如果要使用 non-blocking 消息框的对话结果并根据结果执行作业:

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");
});

注:

  • Task.Run 之后的代码立即运行,而不考虑消息框。